问题描述
目的:使用STL中的vector模板,设计并实现顺序表应用场合的一些简单算法设计。
应用4:试设计一个算法,将所有在线性表LB中但不在LA中的数据元素插入到LA中,算法执行之后,线性表LB不再存在。
参考函数原型:
template<class ElemType>
void Union_Sq( vector<ElemType> &LA,vector<ElemType> &LB );
输入说明
第一行:待处理顺序表LA的长度
第二行:待处理顺序表LA的数据元素(数据元素之间以空格分隔)
第三行:待处理顺序表LB的长度
第四行:待处理顺序表LB的数据元素(数据元素之间以空格分隔)
输出说明
第一行:顺序表LA的遍历结果
第二行:顺序表LB的遍历结果
第三行:合并后顺序表LA的遍历结果
输入范例
10
13 5 27 9 32 123 76 98 54 87
10
13 5 13 9 32 51 76 5 54 8
输出范例
13 5 27 9 32 123 76 98 54 87
13 5 13 9 32 51 76 5 54 8
13 5 27 9 32 123 76 98 54 87 51 8
代码实现
#include <vector>
#include <iostream>
using namespace std;
/*
description:show all the elements of the vector
*/
template<class Elemtype>
void show(vector<Elemtype>& A)
{
typename std::vector<Elemtype> test = A;
typename std::vector<Elemtype>::iterator iter;
for(iter = test.begin();iter != test.end();iter ++)
{
cout<<*iter<<" ";
}
cout<<endl;
}
/*
description:request the combining set of two lists with different elements
*/
template<class Elemtype>
void Union_Sq(vector<Elemtype> &LA,vector<Elemtype> &LB)
{
show(LA);
show(LB);
cout<<endl;
bool isFlag = true;
typename std::vector<Elemtype>::iterator iterA = LA.begin();
typename std::vector<Elemtype>::iterator iterB = LB.begin();
while(iterB != LB.end())
{
iterA = LA.begin();
while(iterA != LA.end())
{
if(*iterA == *iterB)
{
isFlag = false;
break;
}
iterA ++;
}
if(isFlag)
{
LA.push_back(*iterB);
}
isFlag = true;
iterB ++;
}
show(LA);
}
int main()
{
int Asize;
cin>>Asize;
vector<string> A(Asize);
string str;
for(int i = 0 ;i < Asize;i ++)
{
cin>>str;
A.at(i) = str;
}
int Bsize;
cin>>Bsize;
vector<string> B(Bsize);
for(int i = 0 ;i < Bsize;i ++)
{
cin>>str;
B.at(i) = str;
}
Union_Sq(A,B);
return 0;
}