大家好,很抱歉占用你们的时间!我正在做在线练习,任务是编写一个与set_symmetric_difference相同的模板函数。该函数采用五个参数p1, p2, p3, p4 p5。p1 and p2是第一个块的边界,p3 and p4是第二个块的边界,p5点位于目标块的开头。
注意:有三种不同的参数类型,因为p1和p2可以是指针,而p3和p4可以是迭代器。
函数应该找到两个集合的对称差,但在一定条件下:
x的元素,则不会复制另一个具有相同值的元素)。到目前为止我还没能解决这个问题。我的解决方案在某些情况下有效,但对于另一些情况则不起作用。我完全不知道如何遵守规则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。我不知道怎么修好它。对不起我的无知,如果有人来救我,我会很高兴的!谢谢你无数次了!
发布于 2019-04-18 17:24:29
首先,您的输出将被排序。因此,它需要是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;
}https://stackoverflow.com/questions/55750726
复制相似问题