是否有 find()
列表函数,就像向量中的函数一样?
有没有办法在列表中做到这一点?
原文由 Prasanth Madhavan 发布,翻译遵循 CC BY-SA 4.0 许可协议
是否有 find()
列表函数,就像向量中的函数一样?
有没有办法在列表中做到这一点?
原文由 Prasanth Madhavan 发布,翻译遵循 CC BY-SA 4.0 许可协议
除了使用 std::find
(来自算法)之外,您还可以使用 std::find_if
(即 IMO,比 std::find 更好),或 此列表中 的其他查找算法
#include <list>
#include <algorithm>
#include <iostream>
int main()
{
std::list<int> myList{ 5, 19, 34, 3, 33 };
auto it = std::find_if( std::begin( myList ),
std::end( myList ),
[&]( const int v ){ return 0 == ( v % 17 ); } );
if ( myList.end() == it )
{
std::cout << "item not found" << std::endl;
}
else
{
const int pos = std::distance( myList.begin(), it ) + 1;
std::cout << "item divisible by 17 found at position " << pos << std::endl;
}
}
原文由 BЈовић 发布,翻译遵循 CC BY-SA 4.0 许可协议
3 回答2k 阅读✓ 已解决
2 回答3.9k 阅读✓ 已解决
2 回答3.2k 阅读✓ 已解决
1 回答3.2k 阅读✓ 已解决
1 回答2.7k 阅读✓ 已解决
3 回答3.4k 阅读
1 回答3.3k 阅读
您使用
std::find
来自<algorithm>
,这同样适用于std::list
和std::vector
。std::vector
没有自己的搜索/查找功能。请注意,这适用于内置类型,如
int
以及标准库类型,如std::string
默认情况下,因为它们为它们提供了operator==
。如果您在用户定义类型的容器上使用std::find
,则应重载operator==
以允许std::find
正常工作 - 参见EqualityComparable
概念。