在很久以前自己写过一段关于回文的,近来学了下STL感觉用起来更好,就贴出来看看。#include<iostream> //#include<malloc.h> using namespace std; void huiwen(char str[]) { int i=0,j; j=strlen(str)-1;//sizeof(str[0]); cout<<strlen(str)<<endl; bool sign=true; while(sign)//当i>=j时说明他们的对称为相等从而退出循环 { sign=i<j; if(str[i]!=str[j]) break; else { i++; j--; } } if(sign) { cout<<"str不是回文序"<<endl; } else { cout<<"str是回文序列"<<endl; } } void main() { char str[]="123454321"; huiwen(str); } 下面是用STL Vector实现的 #include<iostream> //#include<string> #include<vector> #include<algorithm> using namespace std; //void ishuwen(const string & strm); int main() { //string strm("12345321"); //ishuwen(strm); vector<char> coll1; vector<char> coll2; char str[]="abcdefgfedcba"; //以下这样做可以达到要求,但必须确保最后的/0结束符有位置 //最好不要这样 //char str[12]; //cin>>str; //以下这样是错误的字符不允许这样做 //char *str; //cin>>str; int num=sizeof(str)/sizeof(str[0]); cout<<"the str's size:"<<num<<endl; copy(str,str+num-1,back_inserter(coll1));//由于字符数组加了"/0"字符所以减一 vector<char>::iterator pos1,pos2; for(pos1=coll1.begin();pos1!=coll1.end();++pos1) { cout<<*pos1<<" "; } cout<<endl; copy(coll1.rbegin(),coll1.rend(),back_inserter(coll2)); for(pos2=coll2.begin();pos2!=coll2.end();++pos2) { cout<<*pos2<<" "; } cout<<endl; //用算法进行判断 if(equal(coll1.begin(),coll1.end(),coll2.begin())) { cout<<"the str is a huwen"<<endl; } else { cout<<"the str is not a huwen"<<endl; } } 下面是用String实现的 #include<iostream> #include<string> //#include<vector> #include<algorithm> using namespace std; int main() { string s1,s2; cout<<"please input the str s1:"<<endl; getline(cin,s1); cout<<"the str s1:"<<s1<<endl; int num; num=s1.size(); cout<<"the str's size():"<<num<<endl; //copy(s1.rbegin(),s1.rend(), //s2(s1); //transform(s1.rbegin(),s1.rend(),back_inserter(s2));一般此函数有5个参数 //copy(s1.rbegin(),s1.rend(),back_inserter(s2)); //s2.assign(s1.rbegin(),s1.rend());//此处运用了string的迭代器操作函数 s2.append(s1.rbegin(),s1.rend());//此处亦是String的迭代器操作函数 cout<<"the str s2:"<<s2<<endl; int x=s1.compare(s2);//调用string的比较操作函数返回0即相等,1为小于,-1为大于相当于equal()函数功能判断相等 if(x==0) { cout<<"the str s1==s2,so the str is huwen!"<<endl; } else { cout<<"the str is not huwen!"<<endl; } }