本文共 1999 字,大约阅读时间需要 6 分钟。
目的:使用STL中的vector模板,设计并实现顺序表应用场合的一些简单算法设计。
应用2:试设计一个算法,实现两个顺序表A、B大小的比较。若 A<B,则返回 -1;若 A=B,则返回 0;若 A>B,则返回 1。
参考函数原型:template
int ListCompare( vector &A,vector &B );第一行:顺序表A的长度
第二行:顺序表A的数据元素(数据元素之间以空格分隔)
第三行:顺序表B的长度
第四行:顺序表B的数据元素(数据元素之间以空格分隔)
第一行:比较结果
(输入与输出之间以空行分隔)
1013 5 27 9 32 123 76 98 54 87813 5 27 9 32 164 5 8
13 5 27 9 32 123 76 98 54 87 13 5 27 9 32 164 5 8 -1
#include#include using namespace std;/* description:find the longgest common public substring*/template int commonSubstring(vector &A,vector &B){ int i = 0; while(i < A.size() && i < B.size()) { if(A.at(i) == B.at(i)) { i ++; } else { return i; } } return i;}/* description:show all the elements of the vector*/template void show(vector & A){ typename std::vector test = A; typename std::vector ::iterator iter; for(iter = test.begin();iter != test.end();iter ++) { cout<<*iter<<" "; } cout< B ,return 1;A int ListCompare(vector &A,vector &B){ int commonIndex = commonSubstring(A,B); A.erase(A.begin(),A.begin() + commonIndex); B.erase(B.begin(),B.begin() + commonIndex); if(A.size() == 0 && B.size() == 0) { return 0; } if((A.size() == 0 && B.size() != 0) || A.at(0) < B.at(0)) { return -1; } if((A.size() != 0 && B.size() == 0) || A.at(0) > B.at(0)) { return 1; }}int main(){ int Asize; cin>>Asize; vector A(Asize); string str; for(int i = 0 ;i < Asize;i ++) { cin>>str; A.at(i) = str; } int Bsize; cin>>Bsize; vector B(Bsize); for(int i = 0 ;i < Bsize;i ++) { cin>>str; B.at(i) = str; } show(A); show(B); cout<
转载地址:http://iwwvb.baihongyu.com/