13

I want to check whether an element exists in the vector or not. I know the below piece of code will check it.

#include <algorithm>

if ( std::find(vector.begin(), vector.end(), item) != vector.end() )
   std::cout << "found";
else
   std::cout << "not found";

But I have the vector of any type. i.e. std::vector<std::any> I am pushing elements into vector like this.

std::vector<std::any> temp;
temp.emplace_back(std::string("A"));
temp.emplace_back(10);
temp.emplace_back(3.14f);

So I need to find whether string "A" present in the vector or not. Can std::find help here?

As of now I am using below piece of code to do this

bool isItemPresentInAnyVector(std::vector<std::any> items, std::any item)
{
    for (const auto& it : items)
    {
        if (it.type() == typeid(std::string) && item.type() == typeid(std::string))
        {
            std::string strVecItem = std::any_cast<std::string>(it);
            std::string strItem = std::any_cast<std::string>(item);

            if (strVecItem.compare(strItem) == 0)
                return true;
        }
        else if (it.type() == typeid(int) && item.type() == typeid(int))
        {
            int iVecItem = std::any_cast<int>(it);
            int iItem = std::any_cast<int>(item);

            if (iVecItem == iItem)
                return true;
        }
        else if (it.type() == typeid(float) && item.type() == typeid(float))
        {
            float fVecItem = std::any_cast<float>(it);
            float fItem = std::any_cast<float>(item);

            if (fVecItem == fItem)
                return true;
        }
    }

    return false;
}
Eric
  • 95,302
  • 53
  • 242
  • 374
Arun
  • 2,247
  • 3
  • 28
  • 51
  • 2
    Read `std::find_if`. – Passer By Mar 08 '19 at 06:51
  • 6
    Have you considered using `std::variant` instead? `std::find` will work fine on that. – Eric Mar 08 '19 at 06:57
  • Generic comparisons of std::any would require support from any itself (since you can't any_cast based on type(), which is not known at compile time); For what you seem to be doing, variant is indeed better along multiple dimensions - no extra heap overhead, no hidden virtual dispatch, etc... – Stefan Atev Mar 08 '19 at 15:58

5 Answers5

10

This should work good I guess:

#include <vector>
#include <string>
#include <any>
#include <algorithm>
#include <iostream>

int main(){
    std::vector<std::any> temp;
    temp.emplace_back(std::string("A"));
    temp.emplace_back(10);
    temp.emplace_back(3.14f);

    int i = 10;//you can use any type for i variable and it should work fine
    //std::string i = "A"; 
    auto found = std::find_if(temp.begin(), temp.end(), [i](const auto &a){
        return typeid(i) == a.type() && std::any_cast<decltype(i)>(a) == i;
    } );

    std::cout << std::any_cast<decltype(i)>(*found);
}

Or to make the code a bit more generic and reusable:

#include <vector>
#include <string>
#include <any>
#include <algorithm>
#include <iostream>


auto any_compare = [](const auto &i){
    return [i] (const auto &val){
        return typeid(i) == val.type() && std::any_cast<decltype(i)>(val) == i;
    };
};

int main(){
    std::vector<std::any> temp;
    temp.emplace_back(std::string("A"));
    temp.emplace_back(10);
    temp.emplace_back(3.14f);

    //int i = 10;
    std::string i = "A";
    auto found = std::find_if(temp.begin(), temp.end(), any_compare(i));

    std::cout << std::any_cast<decltype(i)>(*found);
}

Live demo

Important note: this is guaranteed to work only within single translation unit due to stadard requirements on std::any type (for example same types don't need to have same type identifier in different translation units)

bartop
  • 9,971
  • 1
  • 23
  • 54
  • Notice that `std::find_if(temp.begin(), temp.end(), any_compare(temp[0]))` would fail (`any` of `any`). – Jarod42 Mar 08 '19 at 09:15
  • @Jarod42 for sake of simplicity I ommited it, but I can fix it – bartop Mar 08 '19 at 09:17
  • 1
    @bartop: I would say finding an `any` in a vector of `any` using equal operator is impossible by design (portably). It can be done implementing `std::any` differently, but I don't see how you can end up calling equality comparison in a compilation unit that never saw the types wrapped in the `any` object if the "manager" handling the virtual dispatching doesn't support that operation explicitly (and g++ doesn't because the standard doesn't require it). – 6502 Mar 08 '19 at 11:44
  • @6502 you are right, this will work only with single compilation unit – bartop Mar 11 '19 at 08:55
3

Using an any for this kind of purpose is not a good use of any. The best way to go is just to use a variant - since you have a closed set of types:

struct Equals {
    template <typename T>
    constexpr bool operator()(T const& a, T const& b) const { return a == b; }

    template <typename T, typename U>
    constexpr bool operator()(T const& a, U const& b) const { return false; }
};

using V = std::variant<int, float, std::string>
bool isItemPresentInAnyVector(std::vector<V> const& items, V const& item)
{
    auto it = std::find_if(items.begin(), items.end(), [&](V const& elem){
        return std::visit(Equals{}, elem, item);
    });
    return it != items.end();
}

Actually it's even better, because as Kilian points out, variant's operator== already works exactly like this:

using V = std::variant<int, float, std::string>
bool isItemPresentInAnyVector(std::vector<V> const& items, V const& item)
{
    return std::find(items.begin(), items.end(), item) != items.end();
}
Barry
  • 286,269
  • 29
  • 621
  • 977
  • 1
    In this case you could even use the variants operator== https://en.cppreference.com/w/cpp/utility/variant/operator_cmp . auto it = std::find(items.begin(), items.end(), item); – Kilian Mar 08 '19 at 19:59
2

Unfortunately if you want to find an std::any instance in a vector of std::any instances the answer is no.

std::any does need some "magic" for example to be able to handle the creation of unknown object types but this machinery is private and must only supports object creation and not equality comparison.

It would be possible to implement what you are looking for using the same approach, but not with standard std::any that doesn't publish the needed details. The "manager" template needs to enumerate all possible operations and, for example, in g++ implementation they're "access", "get_type_info", "clone", "destroy", "xfer".

variant is completely different, because explicitly lists all the allowed types and therefore in any place it's used can access all the methods.

6502
  • 112,025
  • 15
  • 165
  • 265
1

Comparison with typeId() should be avoided since it's dependent from translation unit.

A much safer approach can be used with any_cast of pointers:

template<typename T>
std::optional<T> find(const std::vector<std::any>& v)
{
   for(auto&& e : v){
      if(auto ptr = std::any_cast<T>(&e)){
         return *ptr;
      }
   }

   return std::nullopt;
} 

Find first element with the given type, or nullopt if it's not found.

If we want to find all element with a specific instead:

template<typename T>
std::vector<T> findAll(const std::vector<std::any>& v)
{
   std::vector<T> out;
   for(auto&& e : v){
      if(auto ptr = std::any_cast<T>(&e)){
         out.push_back(*ptr);
      }
   }

   return out;
}

Usage:

int main()
{
    std::vector<std::any> temp;
    temp.emplace_back(std::string("A"));
    temp.emplace_back(10);
    temp.emplace_back(3.14f);
    temp.emplace_back(12);
    temp.emplace_back(std::string("B"));
    
    auto outInt = findAll<int>(temp);
    
    std::cout << "out int: " << outInt.size() << std::endl;
    for(auto&& out : outInt)
        std::cout << out << std::endl;
        
    auto outString = findAll<std::string>(temp);
    
    std::cout << "out string: " << outString.size() << std::endl;
    for(auto&& out : outString)
        std::cout << out << std::endl;
        
    auto singleInt = find<int>(temp);
    if(singleInt)
         std::cout << "first int " << *singleInt << std::endl;
         
    auto singleBool = find<bool>(temp);
    if(!singleBool)
         std::cout << "ok: bool not found" << std::endl;
}

LIVE DEMO

Moia
  • 2,216
  • 1
  • 12
  • 34
0

If the types are int, float and string (or a limited set of types), you can use a combination of std::variant and std::get_if to achieve what you want to do in a simple manner:

std::get_if is to determine which of the types is stored in the std::variant.

A minimal example:

#include <iostream>
#include <vector>
#include <string>
#include <variant>

int main(){
    std::vector<std::variant<int, float, std::string>> temp;
    temp.emplace_back(std::string("A"));
    temp.emplace_back(10);
    temp.emplace_back(3.14f);     

    for (const auto& var: temp) {
      if(std::get_if<std::string>(&var)) { 
          if(std::get<std::string>(var) == "A") std::cout << "found string\n"; 
      }
      if(std::get_if<int>(&var)) { 
          if(std::get<int>(var) == 10) std::cout << "found int\n"; 
      }
      if(std::get_if<float>(&var)) { 
          if(std::get<float>(var) == 3.14f) std::cout << "found float\n"; 
      }
    }
}

Live Demo

P.W
  • 26,289
  • 6
  • 39
  • 76