10

我想检查向量中是否存在元素。我知道下面的代码会检查它。

#include <algorithm>

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

但我有任何类型的向量。即std::vector<std::any> 我像这样将元素推入向量中。

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

所以我需要找出向量中是否存在字符串“A”。可以 std::find 帮助吗?

截至目前,我正在使用下面的代码来执行此操作

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;
}
4

5 回答 5

9

我猜这应该很好用:

#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);
}

或者使代码更通用和可重用:

#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);
}

现场演示

重要提示:由于对std::any类型的标准要求,这保证仅在单个翻译单元中有效(例如,相同的类型不需要在不同的翻译单元中具有相同的类型标识符)

于 2019-03-08T07:41:40.000 回答
2

any用于这种目的并不是很好地使用any. 最好的方法就是使用variant- 因为你有一组封闭的类型:

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();
}

实际上它甚至更好,因为正如 Kilian 指出的那样,variant'operator==已经完全像这样工作:

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();
}
于 2019-03-08T16:18:26.413 回答
2

不幸的是,如果您想在std::any实例向量中找到一个实例,std::any答案是否定的。

std::any确实需要一些“魔法”,例如能够处理未知对象类型的创建,但这种机制是私有的,必须只支持对象创建而不支持相等比较。

可以使用相同的方法来实现您正在寻找的东西,但不能使用std::any不发布所需细节的标准。“manager”模板需要枚举所有可能的操作,例如,在 g++ 实现中,它们是“access”、“get_type_info”、“clone”、“destroy”、“xfer”。

variant完全不同,因为明确列出了所有允许的类型,因此在任何使用它的地方都可以访问所有方法。

于 2019-03-08T09:16:13.703 回答
1

typeId()应该避免比较,因为它依赖于翻译单元。

any_cast使用of 指针可以使用更安全的方法:

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;
} 

查找具有给定类型的第一个元素,或者nullopt如果未找到。

如果我们想找到具有特定元素的所有元素:

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;
}

用法:

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;
}

现场演示

于 2021-01-21T10:21:15.833 回答
0

如果类型是int, floatand string(或一组有限的类型),您可以使用std::variant和的组合std::get_if以简单的方式实现您想要做的事情:

std::get_if是确定哪些类型存储在std::variant.

一个最小的例子:

#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"; 
      }
    }
}

现场演示

于 2019-03-08T07:52:30.173 回答