问题描述
目的:使用STL中的vector模板,设计并实现顺序表应用场合的一些简单算法设计。
应用6:假设以两个元素依值递增有序排列的线性表A和B分别表示两个集合(即同一表中的元素值各不相同),现要求设计一个算法,另辟空间构成一个线性表C,其元素为A和B中元素的交集,且C中的元素也依值递增有序排列。
参考函数原型:
template<class ElemType>
void Intersect_Sq_OL_C( const vector<ElemType> &A, const vector<ElemType> &B, vector<ElemType> &C );
输入说明
第一行:有序顺序表A的长度
第二行:有序顺序表A的数据元素(数据元素之间以空格分隔)
第三行:有序顺序表B的长度
第四行:有序顺序表B的数据元素(数据元素之间以空格分隔)
输出说明
第一行:顺序表A的遍历结果
第二行:顺序表B的遍历结果
第三行:顺序表C的遍历结果
输入范例
5
1 3 5 7 9
8
1 2 3 4 5 6 9 11
输出范例
1 3 5 7 9
1 2 3 4 5 6 9 11
1 3 5 9
代码实现
#include <iostream>
#include <vector>
using namespace std;
/*
description:function to compare two elements
*/
template<class Elemtype>
void sort(vector<Elemtype> &A)
{
Elemtype temp;
for(int i = 0;i < A.size();i ++)
{
for(int j = i + 1;j < A.size();j ++)
{
if(A.at(i) > A.at(j))
{
temp = A.at(i);
A.at(i) = A.at(j);
A.at(j) = temp;
}
}
}
}
/*
description:show all the elements of the vector
*/
template<class Elemtype>
void show(const 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;
}
template<class ElemType>
void Intersect_Sq_OL_C( const vector<ElemType> &A
, const vector<ElemType> &B
, vector<ElemType> &C )
{
show(A);
show(B);
cout<<endl;
bool isFlag = false;
for(int i = 0 ;i < A.size();i ++)
{
for(int j = 0;j < B.size(); j++)
{
if(A.at(i) == B.at(j))
{
isFlag = true;
break;
}
}
if(isFlag)
{
C.push_back(A.at(i));
isFlag = false;
}
}
show(C);
}
int main()
{
int Asize;
cin>>Asize;
string str;
cin>>str;
if(str == "a")
{
vector<string> A(Asize);
A.at(0) = str;
for(int i = 1 ; 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;
}
vector<string> C;
Intersect_Sq_OL_C(A,B,C);
}
else
{
vector<int> B(Asize);
B.at(0) = atoi(str.c_str());
int temp;
for(int i = 1 ; i < Asize; i ++) {
cin>>temp;
B.at(i) = temp;
}
int Bsize;
cin>>Bsize;
vector<int> B1(Bsize);
for(int i = 0 ; i < Bsize;i ++)
{
cin>>temp;
B1.at(i) = temp;
}
vector<int> C;
Intersect_Sq_OL_C(B,B1,C);
}
return 0;
}
分析与总结
- 注意审题,题目已经说明了,所有的元素都是唯一的,并且都是已经排过序的。没有重复的,所以不需要去除重复。