我要做的就是检查向量中是否存在一个元素,这样我就可以处理每一种情况。
if ( item_present )
do_this();
else
do_that();
我要做的就是检查向量中是否存在一个元素,这样我就可以处理每一种情况。
if ( item_present )
do_this();
else
do_that();
当前回答
你可以试试下面的代码:
#include <algorithm>
#include <vector>
// You can use class, struct or primitive data type for Item
struct Item {
//Some fields
};
typedef std::vector<Item> ItemVector;
typedef ItemVector::iterator ItemIterator;
//...
ItemVector vtItem;
//... (init data for vtItem)
Item itemToFind;
//...
ItemIterator itemItr;
itemItr = std::find(vtItem.begin(), vtItem.end(), itemToFind);
if (itemItr != vtItem.end()) {
// Item found
// doThis()
}
else {
// Item not found
// doThat()
}
其他回答
记住,如果你要做大量的查找,有STL容器会更好。我不知道你的应用程序是什么,但是像std::map这样的关联容器可能值得考虑。
vector是容器的选择,除非您有其他原因,按值查找就是这样一个原因。
你可以使用std::find from <algorithm>:
#include <algorithm>
#include <vector>
vector<int> vec;
//can have other data types instead of int but must same datatype as item
std::find(vec.begin(), vec.end(), item) != vec.end()
这将返回找到的第一个元素的迭代器。如果不存在,则返回一个指向倒数一的迭代器。用你的例子:
#include <algorithm>
#include <vector>
if ( std::find(vec.begin(), vec.end(), item) != vec.end() )
do_this();
else
do_that();
你可以使用find函数,在std命名空间中找到,即std::find。向std::find函数传递要搜索的向量的begin迭代器和end迭代器,以及要查找的元素,并将结果迭代器与向量的结束迭代器进行比较,以查看它们是否匹配。
std::find(vector.begin(), vector.end(), item) != vector.end()
您还可以解除对该迭代器的引用,并像其他迭代器一样正常使用它。
从c++ 20开始,使用range (#include <ranges>)
//SAMPLE DATA
std::vector<int> vecOfElements = { 2,4,6,8 };
//DO SOMETHING IF 8 IN VECTOR
if (std::ranges::find(vecOfElements, 8) != vecOfElements.end())
{
std::cout << "DO SOMETHING" << std::endl;
}
如果你想在向量中找到一个字符串:
struct isEqual
{
isEqual(const std::string& s): m_s(s)
{}
bool operator()(OIDV* l)
{
return l->oid == m_s;
}
std::string m_s;
};
struct OIDV
{
string oid;
//else
};
VecOidv::iterator itFind = find_if(vecOidv.begin(), vecOidv.end(), isEqual(szTmp));