Compare two C ++ vectors

I was wondering if there is any function to compare two string vectors in order to return the number of different (or identical) elements? Or I need to iterate over both of them and test on the elements.
Thank.

+15
c ++ stl
Mar 07 2018-11-11T00:
source share
3 answers
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 do not want to sort:

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

You might want to use a multiset if there might be duplicates in the vector.

+39
Mar 07 2018-11-22T00:
source share

I do not know about the existing function, but writing it yourself should not be too complicated.

 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 short
  • This function needs to be updated if it should handle instances of vector<string> different lengths.
+4
Mar 07 2018-11-11T00:
source share

See set_difference () and set_intersection () . In both cases, you need to sort your containers in advance.

+3
Mar 07 '11 at 10:10
source share



All Articles