如何在 stl 列表中搜索元素?

新手上路,请多包涵

是否有 find() 列表函数,就像向量中的函数一样?

有没有办法在列表中做到这一点?

原文由 Prasanth Madhavan 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 546
2 个回答

您使用 std::find 来自 <algorithm> ,这同样适用于 std::liststd::vectorstd::vector 没有自己的搜索/查找功能。

 #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 概念

原文由 wkl 发布,翻译遵循 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 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题