编写执行与set_symmetric_difference相同的作业的函数

Writing a function that performs the same job as set_symmetric_difference

本文关键字:函数 difference 作业 symmetric 执行 set      更新时间:2023-10-16

大家好,很抱歉占用时间! 我正在做在线练习,我的任务是编写一个与set_symmetric_difference相同的模板函数。该函数采用五个参数p1, p2, p3, p4 p5p1 and p2是第一个块的边界,p3 and p4第二个块的边界,p5目标块开头的点。

注意:有三种不同的参数类型,因为 p1 和 p2 可以是指针,而 p3 和 p4 可以是迭代器。

该函数应找到两个集合的对称差,但具有某些条件:

  1. 不允许重复(即,如果对称差分集中已经存在值x的元素,则不会复制另一个具有相同值的元素)。

  2. 所有元素必须与原始两个块的顺序相同

  3. 第一个块的元素将在第二个块的元素之前复制

  4. 该函数返回一个迭代器/指针,
  5. 该迭代器/指针不指向目标块的开头,而是指向块中最后一个元素之后的点。

到目前为止,我在解决这个问题方面没有运气。我的解决方案适用于某些实例,但对于其他情况则不起作用。我完全不知道如何遵循规则 1、2 和 3。

#include <iostream>
#include <algorithm>
#include <vector>
#include <deque>
using namespace std;
template <typename type1, typename type2, typename type3> 
type3 symmetric(type1 p1, type1 p2, type2 p3, type2 p4, type3 p5) {
sort(p1,p2);
sort(p3,p4);
while(true) {
if(p1 == p2) return copy(p3,p4,p5); 
if(p3==p4) return copy(p1,p2,p5);
if(*p1 < *p3) {
*p5=*p1;
p5++;
p1++;
}
else if(*p3 < *p1) {
*p5 = *p3;
p3++;
p5++;
}
else {
p1++;
p3++;
}
}
return p5;
}
int main ()
{
int block1[] = { 5, 2, 7, 4, 6, 1, 3, 2, 7, 4 };
int block2[] = { 2, 9, 0, 6, 0, 4, 8, 3, 2, 5 };
int destination[10];
auto p = symmetric(block1, block1+10, block2, block2+10, destination);
auto destination_begin = destination;
while(destination_begin < p) cout << *destination_begin++;
return 0;
}

对于我提到的示例,输出应该是7 1 9 0 8但我的程序打印0 0 1 4 7 7 8 9。我不知道如何解决它。对不起我的无知,如果有人来救我,我会很高兴!感谢一百万次!

首先,您的输出应该被排序。因此,它需要0 1 7 8 9,而不是7 1 9 0 8

代码中缺少的关键逻辑部分是在循环访问输入列表时不会跳过重复的条目。

这是您发布的代码的更新版本,适用于我。

#include <iostream>
#include <algorithm>
#include <vector>
#include <deque>
using namespace std;
template <typename type> 
void print(type p1, type p2)
{
while(p1 != p2) cout << *p1++ << " ";
cout << endl;
}
template <typename type> 
type skip_duplicates(type p)
{
while ( *p == *(p+1) ) ++p;
return ++p;
}
template <typename type1, typename type2, typename type3> 
type3 symmetric(type1 p1, type1 p2, type2 p3, type2 p4, type3 p5) {
sort(p1,p2);
sort(p3,p4);
print(p1, p2);
print(p3, p4);
while(true) {
if(p1 == p2) return copy(p3,p4,p5); 
if(p3 == p4) return copy(p1,p2,p5);
if(*p1 < *p3) {
*p5=*p1;
p5++;
p1 = skip_duplicates(p1);
}
else if(*p3 < *p1) {
*p5 = *p3;
p3 = skip_duplicates(p3);
p5++;
}
else {
p1 = skip_duplicates(p1);
p3 = skip_duplicates(p3);
}
}
return p5;
}
int main ()
{
int block1[] = { 5, 2, 7, 4, 6, 1, 3, 2, 7, 4 };
int block2[] = { 2, 9, 0, 6, 0, 4, 8, 3, 2, 5 };
int destination[10];
auto p = symmetric(block1, block1+10, block2, block2+10, destination);
print(destination, p);
return 0;
}