[英]is there std::mismatch for two unequal sized vectors?
我想比较两个向量,其中第二个可能有比第一个更多/更少的项目。
v1 = 1,2,3,4,5
v2 = 1,0,3,4,5,6
据我所知, std::mismatch
woNT可以解决问题。 我如何检测v1中缺少的元素?
提前致谢,
Orkun
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 );
您可以通过在gcc和clang上设置-std=c++1y
来使用它们
使用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));
在此之后,这两个向量的所有不同元素(即在v1
或v2
,但不是两者)都将存储在vector<int> vDifferences
。 对于您的示例,它将是{0, 2, 6}
。
[...]计算两个有序范围的对称差异:在任一范围中找到但在两个范围内都找不到的元素将被复制到从d_first开始的范围。 结果范围也是排序的。 [...]
如果你只需要在缺少元素v1
,则可以进一步扫描该vDifferences
对sortedV1
找出来。
查看此讨论以获取更多信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.