【问题标题】:is there std::mismatch for two unequal sized vectors?两个大小不等的向量是否存在 std::mismatch ?
【发布时间】:2014-01-22 16:06:25
【问题描述】:

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

v1 = 1,2,3,4,5

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

据我了解,std::mismatch 不会成功。如何检测 v1 中缺失的元素?

提前致谢,

奥昆

【问题讨论】:

标签: c++ algorithm vector std


【解决方案1】:

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 来使用这些

【讨论】:

  • C++14 支持目前可能有点乐观!
  • @Sean 实际上,libstdc++ doesn't 包含这些重载,但是查看最新的 libc++ source 我可以找到它们。所以 clang + libc++ 可能是一个选择。编辑:最新的 libstdc++ source 也包含它们。
【解决方案2】:

使用 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&lt;int&gt; vDifferences 中。对于您的示例,它将是 {0, 2, 6}

[...] 计算两个排序范围的对称差:在任一范围内找到但不在这两个范围内的元素被复制到从 d_first 开始的范围内。结果范围也被排序。 [...]

如果您只需要v1 中缺少的元素,您可以进一步扫描此vDifferencessortedV1 以找出它们。

查看this discussion 了解更多信息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-10
    • 1970-01-01
    • 2012-10-10
    • 1970-01-01
    • 1970-01-01
    • 2021-05-23
    • 1970-01-01
    相关资源
    最近更新 更多