【发布时间】:2019-07-30 04:11:27
【问题描述】:
我想检查一个元素是否存在于向量中。我知道下面的代码会检查它。
#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:: 可以在这里找到帮助吗?
到目前为止,我正在使用以下代码来执行此操作
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;
}
【问题讨论】:
-
阅读
std::find_if。 -
您是否考虑过改用
std::variant<int, float, std::string>?std::find可以正常工作。 -
std::any 的通用比较需要 any 本身的支持(因为您不能基于 type() 进行 any_cast,这在编译时是未知的);对于您似乎正在做的事情,variant 在多个维度上确实更好 - 没有额外的堆开销,没有隐藏的虚拟调度等......