在std :: vector的std :: vector中找到一个元素

Aru*_*run 6 c++ c++17 stdany

我想检查向量中是否存在元素。我知道下面的代码将对其进行检查。

#include <algorithm>

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

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

std::vector<std::any> temp;
temp.emplace_back(std::string("A"));
temp.emplace_back(10);
temp.emplace_back(3.14f);
Run Code Online (Sandbox Code Playgroud)

因此,我需要查找向量中是否存在字符串“ 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;
}
Run Code Online (Sandbox Code Playgroud)

bar*_*top 5

我猜这应该工作良好:

#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);
}
Run Code Online (Sandbox Code Playgroud)

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

#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);
}
Run Code Online (Sandbox Code Playgroud)

现场演示

重要说明:由于对标准的标准要求,这保证只能在单个翻译单元中工作std::any(例如,相同的类型在不同的翻译单元中不需要具有相同的类型标识符)