2014-01-22 33 views
3

我想比較兩個向量,其中第二個向量可能比第一個向量更多/更少。是否存在兩個不相等大小的向量的std :: mismatch?

v1 = 1,2,3,4,5 

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

據我瞭解,std::mismatch工作的竅門。我如何檢測v1中缺失的元素?

由於提前,

Orkun

+0

對它們進行排序和對比。 – herohuyongtao

+0

您是否嘗試過set_difference? http://www.cplusplus.com/reference/algorithm/set_difference/ – Trenin

+0

或簡單地比較'=='的向量。 – Trenin

回答

2

C++ 14增加了兩個additional overloads,可容納不同大小的範圍

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

你也許可以通過在gcc和鐺設置-std=c++1y使用這些

+1

C++ 14支持目前可能有點樂觀! – Sean

+2

@Sean確實,libstdC++ [不](http://coliru.stacked-crooked.com/a/894d25237202ccdf)包含那些重載,但是看最新的libC++ [source](http://llvm.org/ svn/llvm-project/libcxx/trunk/include/algorithm)我可以找到它們兩個。所以clang + libC++可能是一個選項。編輯:最新的libstdC++ [源代碼](http://repo.or.cz/w/official-gcc.git/blob/HEAD:/libstdc%2B%2B-v3/include/bits/stl_algobase.h#l1334)也包括他們。 – Praetorian

1

使用set_symmetric_difference(),bu t之前必須訂購源範圍:

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

此後,這兩個向量的所有不同元素(即,在v1v2,但不是兩者)將被存儲在vector<int> vDifferences。舉例來說,它將是{0, 2, 6}

[...]計算兩個分類範圍的對稱差:即在任一範圍的發現,而不是在兩者都被複制到在範圍開始d_first的元素。結果範圍也被排序。 [...]

如果你只需要在v1缺少的元素,您可以進一步掃描該vDifferencessortedV1找出來。

查看更多信息this discussion