STL set_symmetric_difference 用法 [英] STL set_symmetric_difference usage

查看:27
本文介绍了STL set_symmetric_difference 用法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在解决一个编程问题,它想找到两个集合之间的对称差异.我已经使用 STL 的 set_symmetric_difference 解决了它.我得到两个 vectorsAB:

I was solving a programming problem, which wants to find the SYMMETRIC DIFFERENCE between two sets. I have solved it using STL's set_symmetric_difference. I am given two vector<int>s, A and B:

A = {342,654,897,312,76,23,78}

A = {342,654,897,312,76,23,78}

B = {21,43,87,98,23,756,897,234,645,876,123}

B = {21,43,87,98,23,756,897,234,645,876,123}

Soul return(正确答案):

Sould return (correct answer):

{ 21,43,76,78,87,98,123,234,312,342,645,654,756,876 }

{ 21,43,76,78,87,98,123,234,312,342,645,654,756,876 }

但我明白了:

{ 21,43,76,78,87,98,123,234,312,342,645,65,756,876}

{ 21,43,76,78,87,98,123,234,312,342,645,65,756,876}

有什么问题?这是我的代码:

What is the problem ? Here is my code:

sort(A.begin(), A.end());
sort(B.begin(), B.end());
// allocate the smallest size of A,B as maximum size
vector<int> c(A.size() < B.size() ? B.size() : A.size());
vector<int>::iterator i;
i = set_symmetric_difference(A.begin(), A.end(), B.begin(), B.end(), c.begin());
return vector<int>(c.begin(), i);

注意:我得到了其余示例的正确答案.这个例子只给了我这个错误的答案.

NOTE: I get correct answers for the rest of examples. This example only gives me this wrong answer.

我在 Visual Studio 中对其进行了测试,并收到一条错误消息:Iterator not incrementable"

I have tested it in Visual Studio, and got an error message: "Iterator not incrementable"

推荐答案

问题在于vector c的初始化.逻辑有点错误,因为输出范围的最大大小可能与两个输入范围的总和一样大.由于您不知道先验大小,因此最好从一个空的输出向量开始,并使用带有 std::back_inserter 代替:

The problem is in the initialization of vector c. The logic is slightly wrong in that the maximum size of the output range could be as large as the sum of the two input ranges. Since you don't know the size a priori, you could be better off by starting with an empty output vector, and using push_back with an std::back_inserter instead:

sort(A.begin(), A.end());
sort(B.begin(), B.end());
std::vector<int> c;
set_symmetric_difference(A.begin(), A.end(), 
                         B.begin(), B.end(), std::back_inserter(c));
return c;

这会产生

21 43 76 78 87 98 123 234 312 342 645 654 756 876

21 43 76 78 87 98 123 234 312 342 645 654 756 876

这篇关于STL set_symmetric_difference 用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆