Adrian
Adrian

Reputation: 20068

How do I get the number of different or common elements between two vectors of strings?

Is there a function to compare two string vectors to return the number of different (or the same) elements? Do I have to iterate over both of them and test item by item?

Upvotes: 24

Views: 58603

Answers (4)

Erik
Erik

Reputation: 91270

// C++20
std::ranges::sort(v1);
std::ranges::sort(v2);
std::vector<std::string> v3;
std::ranges::set_intersection(v1, v2, std::back_inserter(v3));

// any version
std::sort(v1.begin(), v1.end());
std::sort(v2.begin(), v2.end());
std::vector<string> v3;
std::set_intersection(v1.begin(), v1.end(), v2.begin(), v2.end(), std::back_inserter(v3));

Or, if you don't want to sort:

std::set<std::string> s1(v1.begin(), v1.end());
std::set<std::string> s2(v2.begin(), v2.end());
std::vector<std::string> v3;

// C++20
std::ranges::set_intersection(s1, s2, std::back_inserter(v3));
// any version
std::set_intersection(s1.begin(), s1.end(), s2.begin(), s2.end(), std::back_inserter(v3));

You may want to use a multiset if there could be duplicates in a vector.

Upvotes: 46

Build Succeeded
Build Succeeded

Reputation: 1150

if (vector1 == vector2)
{
    DoSomething();
}

The content will be compared from both vectors as per the below link documentation:

Compares the contents of two vectors.

1-2) Checks if the contents of lhs and rhs are equal, that is, they have the same number of elements and each element in lhs compares equal with the element in rhs at the same position.

https://en.cppreference.com/w/cpp/container/vector/operator_cmp

Upvotes: 2

Morten Kristensen
Morten Kristensen

Reputation: 7613

Have a look at set_difference() and set_intersection(). In both cases you need to have your containers sorted beforehand.

Upvotes: 5

JaredPar
JaredPar

Reputation: 754725

I don't know of an existing function but writing one yourself shouldn't be too much trouble.

int compare(const vector<string>& left, const vector<string>& right) {
  auto leftIt = left.begin();
  auto rightIt = right.begin();
  auto diff = 0;
  while (leftIt != left.end() && rightIt != right.end()) {
    if (*leftIt != *rightIt) {
      diff++;
    }
    leftIt++;
    rightIt++;
  }

  // Account for different length vector instances
  if (0 == diff && (leftIt != left.end() || rightIt != right.end())) {
    diff = 1;
  }

  return diff;
}

Notes

  • Omitted std:: prefix for brevity
  • This function needs to be updated if it should handle vector<string> instances of different lengths

Upvotes: 5

Related Questions