Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c++11

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::vectors in C++? (C++11 is allowed)

like image 989
888 Avatar asked Sep 01 '25 03:09

888


2 Answers

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());});
like image 86
WhozCraig Avatar answered Sep 03 '25 13:09

WhozCraig


You need to write your own function something like this:

for (auto element : List1)
{
  auto it = std::find(List2.begin(), List2.end(), element);
  if(it == List2.end())
  {
     result.push_back(element);
  }
}
like image 38
Asha Avatar answered Sep 03 '25 13:09

Asha