获取不属于另一个向量的所有向量元素

888*_*888 3 c++ vector c++11

在 C# 中,如果我想获取 a 中List List1不属于另一个的所有元素,List List2我可以做

var result List1.Except(List2);
Run Code Online (Sandbox Code Playgroud)

std::vector在 C++ 中是否有与s等效的东西?(允许使用 C++11)

Who*_*aig 6

以下内容使用 List1 中不在 List2 中的内容填充 List3。我希望这是你正在寻找的:

std::vector<Type> List1, List2;
//
// populate List1 and List2
//

std::vector<Type> List3;
std::copy_if(List1.begin(), List1.end(), std::back_inserter(List3),
     [&List2](const Type& arg)
     { return (std::find(List2.begin(), List2.end(), arg) == List2.end());});
Run Code Online (Sandbox Code Playgroud)

或者,这可能性能更好,因为您不必搜索整个列表来确定不存在。相反,您可以获得早期的“命中”并移动到下一个节点。注意谓词中的逻辑翻转:

std::vector<Type> List3;
std::remove_copy_if(List1.begin(), List1.end(), std::back_inserter(List3),
     [&List2](const Type& arg)
     { return (std::find(List2.begin(), List2.end(), arg) != List2.end());});
Run Code Online (Sandbox Code Playgroud)