Amr*_*del 0 c++ vector std find c++11
如果有向量,我们需要找到具有相同条件的多个项目.如果我们调用std::find_if它将返回条件的第一次出现.
std::vector <int> List{0,1,2,3,4,5,6};
auto item = find_if(List.begin(), List.end(), [](int x)
{
return x > 2;
}
);
Run Code Online (Sandbox Code Playgroud)
我知道我们可以使用std::for_each并将条件和动作放在lambda表达式中,但我问是否有一个方法可以自己完成并返回找到的项目的向量.
您可以使用std::copy_if填充满足谓词的项的副本的向量.
#include <vector> // vector
#include <iterator> // copy_if
#include <algorithm> // back_inserter
int main()
{
std::vector<int> List{0,1,2,3,4,5,6};
std::vector<int> good_items;
std::copy_if(List.begin(), List.end(), std::back_inserter(good_items),
[](int x) { return x > 2; });
}
Run Code Online (Sandbox Code Playgroud)