c++ - 在 C++ 中迭代列表并搜索另一个列表中的每个元素

标签 c++ list search iterator element

我创建了一个包含 4 个元素的列表,称为“工作列表”。我有另一个名为“choicelist”的列表,其中包含大约 40 个元素。我想检查“worklist”中的任何元素是否存在于“choicelist”中。

我知道我会使用“std::find”进行搜索,但是我将如何按照“choicelist”中“worklist”的顺序检查每个元素?

请记住,一旦在“choicelist”中找到“worklist”中的元素,我希望搜索过程结束(最好是有关“worklist”中哪个元素是第一个匹配的某种通知)。

最佳答案

您必须迭代第一个列表的元素,并使用 find 函数检查它是否存在于第二个列表中。如果找到搜索元素,则打印它并中断循环。

std::list<int> worklist;
std::list<int> choicelist;
//This loop only works in C++11 and above, 
//in case of C++98, you need to use iterators to iterate over list
for( auto &x : worklist) 
{
        //auto is also a feature of C++11 and above
        auto y = std::find (std::begin(choicelist),
                            std::end(choicelist), x);

        if( y != choicelist.end())
        {
            std::cout<< *y<<"\n";
            break;
        }
 }

如果您只需要在第二个容器中查找第一个容器的第一个元素,

auto y= std::find_first_of(std:begin(choicelist), std::end(choicelist),
                           std::begin(worklist), std::end(worklist));
if( y != choicelist.end())
{
                std::cout<< *y<<"\n";
}

关于c++ - 在 C++ 中迭代列表并搜索另一个列表中的每个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29608520/

相关文章:

Java:在对象数组中搜索 2 个特定对象值

search - 如何避免遗传算法中的无效搜索空间?

sharepoint - 如何从 SharePoint 更改搜索核心结果 Web 部件的设计?

c++ - 绝对致命的 wxWidgets 痛苦

c++ - C++ 中的崩溃处理程序

c++ - 在 Eclipse 中使用 C++ 在 Linux 中获取环境变量 $PATH

计算 h 指数

r - lapply 并申请列表 R 的每个组件和元素

c++ - 很好地初始化结构的 union

c++ - 在双向链表中间插入节点