我创建了一个包含 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/