3

I d like to compare two vectors where the second one might have more/less items than the first one.

v1 = 1,2,3,4,5

v2 = 1,0,3,4,5,6

As far as I understood, std::mismatch woNT do the trick. How could I detect the missing element in the v1?

Thanks in advance,

Orkun

Orkun
  • 6,998
  • 8
  • 56
  • 103

2 Answers2

3

C++14 adds two additional overloads that accommodate different sized ranges

template< class InputIt1, class InputIt2 >
std::pair<InputIt1,InputIt2>
    mismatch( InputIt1 first1, InputIt1 last1,
              InputIt2 first2, InputIt2 last2 );

template< class InputIt1, class InputIt2, class BinaryPredicate >
std::pair<InputIt1,InputIt2>
    mismatch( InputIt1 first1, InputIt1 last1,
              InputIt2 first2, InputIt2 last2,
              BinaryPredicate p );

You might be able to use these by setting -std=c++1y on gcc and clang

Praetorian
  • 106,671
  • 19
  • 240
  • 328
  • 1
    C++14 support might be a bit optimistic at the moment! – Sean Jan 22 '14 at 16:43
  • 2
    @Sean Indeed, libstdc++ [doesn't](http://coliru.stacked-crooked.com/a/894d25237202ccdf) contain those overloads, but looking at the latest libc++ [source](http://llvm.org/svn/llvm-project/libcxx/trunk/include/algorithm) I can find both of them. So clang + libc++ might be an option. Edit: The latest libstdc++ [source](http://repo.or.cz/w/official-gcc.git/blob/HEAD:/libstdc%2B%2B-v3/include/bits/stl_algobase.h#l1334) includes them too. – Praetorian Jan 22 '14 at 16:50
1

Use set_symmetric_difference(), but before this the source ranges must be ordered:

vector<int> v1;
vector<int> v2;

// ... Populate v1 and v2

// For the set_symmetric_difference algorithm to work, 
// the source ranges must be ordered!    
vector<int> sortedV1(v1);
vector<int> sortedV2(v2);

sort(sortedV1.begin(),sortedV1.end());
sort(sortedV2.begin(),sortedV2.end());

// Now that we have sorted ranges (i.e., containers), find the differences    
vector<int> vDifferences;

set_symmetric_difference(
    sortedV1.begin(), sortedV1.end(),
    sortedV2.begin(), sortedV2.end(),
    back_inserter(vDifferences));

After this, all different elements of these two vectors (i.e. either in v1 or v2, but not both) will be stored in vector<int> vDifferences. For your example, it will be {0, 2, 6}.

[...] Computes symmetric difference of two sorted ranges: the elements that are found in either of the ranges, but not in both of them are copied to the range beginning at d_first. The resulting range is also sorted. [...]

If you just need the missing elements in the v1, you can further scan this vDifferences against sortedV1 to find them out.

Check out this discussion for more info.

Community
  • 1
  • 1
herohuyongtao
  • 49,413
  • 29
  • 133
  • 174