888 888 - 1 month ago 10
C++ Question

Get all vector elements that don't belong to another vector

In C# if I want to get all elements in a

List List1
, which don't belong to another
List List2
I can do

var result List1.Except(List2);


Is there something equivalent for
std::vector
s in C++? (C++11 is allowed)

Answer

The following populates List3 with the content from List1 that is not in List2. I hope it is what you're looking for:

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());});

Alternatively, this is likely better performing, since you don't have to search the entire list to determine lack of existence. Rather you can get an early "hit" and just move to the next node. Note the logic flip in the predicate:

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());});
Comments