想实现的功能是讲两个队列中不重复的部分加起来
这是主函数里的代码
Queue a, b;
a.push(1);
a.push(2);
a.push(3);
b.push(3);
b.push(4);
b.push(5);
Queue c, d;
cout << "a + b = ";
c = a + b;
cout<< c. back();
这是实现文件中的代码
template
Queue Queue::operator+(Queue obj)
{
int ahead = head;
Queue ans;
type temp;
while(!isEmpty())
{
ans.push(front());
pop();
}
head = ahead;
while(!obj.isEmpty())
{
temp = obj.front();
obj.pop();
while(!isEmpty())
{
if(temp == front())
{
break;
}
pop();
}
if(isEmpty())
ans.push(temp);
head = ahead;
}
head = ahead;
cout << ans.back() << endl;
return ans;
}
是把a和b中不重复的元素合并到一个容器中吗?感觉逻辑不对啊,Queue自身的数据在第一个while循环中已经全部弹出了,在第二个while循环中本队列中已经没有数据了。代码修改如下:(如果不行的话,建议你把全部代码用代码段贴出来,帮你修改一下,只有这些代码没法调试)
template <typename type>
Queue Queue::operator+(Queue obj)
{
Queue ans,tt;
int flag = 0; //是否存在标记
type temp,data;
while(!obj.isEmpty())
{
temp = obj.front();
obj.pop();
//判断temp是否在本队列中
flag = 0;
while(!isEmpty())
{
data = front();
pop(); //从本队列中弹出
if(temp == data)
{
flag = 1;
break;
}
tt.push(data); //先存到tt中
}
if(flag)
ans.push(temp);
//把tt中的数据存入本身
while(!tt.empty())
{
push(tt.front());;
tt.pop();
}
}
return ans;
}
代码段贴代码:点击下面的图标,然后再粘贴代码即可。