如何搜索stl列表中的元素? [英] How to search for an element in an stl list?
问题描述
有向量中有 find()
函数吗?
推荐答案
您可以使用< algorithm> 的cpp / algorithm / find> std :: find
好的 std :: list
和 std :: vector
。 std :: vector
没有自己的搜索/查找功能。
You use std::find
from <algorithm>
, which works equally well for std::list
and std::vector
. std::vector
does not have its own search/find function.
#include <list>
#include <algorithm>
int main()
{
std::list<int> ilist;
ilist.push_back(1);
ilist.push_back(2);
ilist.push_back(3);
std::list<int>::iterator findIter = std::find(ilist.begin(), ilist.end(), 1);
}
请注意,这适用于内置类型 int
以及标准库类型,如 std :: string
,因为它们有 operator ==
为他们提供。如果你在用户定义类型的容器上使用 std :: find
,你应该重载 operator ==
允许 std :: find
正常工作: EqualityComparable
概念
Note that this works for built-in types like int
as well as standard library types like std::string
by default because they have operator==
provided for them. If you are using using std::find
on a container of a user-defined type, you should overload operator==
to allow std::find
to work properly: EqualityComparable
concept
这篇关于如何搜索stl列表中的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!