简体   繁体   English

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

[英]is there std::mismatch for two unequal sized vectors?

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. 据我所知, std::mismatch woNT可以解决问题。 How could I detect the missing element in the v1? 我如何检测v1中缺少的元素?

Thanks in advance, 提前致谢,

Orkun Orkun

C++14 adds two additional overloads that accommodate different sized ranges C ++ 14增加了两个额外的重载 ,适应不同大小的范围

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 您可以通过在gcc和clang上设置-std=c++1y来使用它们

Use set_symmetric_difference() , but before this the source ranges must be ordered: 使用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));

After this, all different elements of these two vectors (ie either in v1 or v2 , but not both) will be stored in vector<int> vDifferences . 在此之后,这两个向量的所有不同元素(即在v1v2 ,但不是两者)都将存储在vector<int> vDifferences For your example, it will be {0, 2, 6} . 对于您的示例,它将是{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. [...]计算两个有序范围的对称差异:在任一范围中找到但在两个范围内都找不到的元素将被复制到从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. 如果你只需要在缺少元素v1 ,则可以进一步扫描该vDifferencessortedV1找出来。

Check out this discussion for more info. 查看此讨论以获取更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM