两个不等大小的向量是否存在std :: mismatch?

时间:2014-01-22 16:06:25

标签: c++ algorithm vector std

我想比较两个向量,其中第二个可能有比第一个更多/更少的项目。

v1 = 1,2,3,4,5

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

据我所知,std::mismatch可以做到这一点。我如何检测v1中缺少的元素?

提前致谢,

Orkun

2 个答案:

答案 0 :(得分: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和clang

上设置-std=c++1y来使用这些功能

答案 1 :(得分:1)

使用 set_symmetric_difference() ,但在此之前必须订购源范围:

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中缺少的元素,则可以针对vDifferences进一步扫描sortedV1以查找它们。

查看this discussion了解详情。