使用vector list等容器对字符串的排序

    xiaoxiao2023-03-24  5

    /**codeblock 测试通过**/ #include <iostream> #include <string> #include <set> #include <list> #include <vector> #include <iterator> #include <algorithm> #include <fstream> using namespace std; string & toLower(string &st); void output(string n){ cout<<n<<" "; } int main(){ string outfile = "result.txt"; //fstream ifn ofstream fout(outfile.c_str(),ios_base::out|ios_base::app); // ofstream fout(outfile.c_str()) if(!fout){ cerr<<"Can't open the file "<<outfile<<endl; return EXIT_FAILURE; } vector<string> one,two; string name; cout<<"请输入姓名:"; while(cin>>name&&name!="quit"){ one.push_back(name); } /*do{ cin>>name; one.push_back(name); }while(name!="quit");*/ //会包含 quit cout<<endl; sort(one.begin(),one.end()); for_each(one.begin(),one.end(),output); cout<<endl; cout<<"请输入姓名:"; while(cin>>name&&name!="quit"){ two.push_back(name); } sort(two.begin(),two.end()); for_each(two.begin(),two.end(),output); cout<<endl; cout<<"合并名单:"; vector<string> three(two); three.insert(three.end(),one.begin(),one.end()); for_each(three.begin(),three.end(),output); //正向显示 for_each(three.rbegin(),three.rend(),output); //逆向显示 cout<<endl; cout<<"排序一:"; sort(three.begin(),three.end()); vector<string>::iterator it = unique(three.begin(),three.end()); if(it != three.end()) three.erase(it,three.end()); // for_each(three.begin(),three.end(),output); cout<<endl; cout<<"排序二:"; //使用list list<string> four; four.insert(four.begin(),three.begin(),three.end()); four.sort(); //排序 four.unique(); //去重 for_each(four.begin(),four.end(),output); cout<<endl<<"排序三:"; //使用set容器 set<string> five(three.begin(),three.end()); for_each(five.begin(),five.end(),output); fout<<"the finnally1 list is:"; vector<string>::iterator pd; for(pd=three.begin();pd!=three.end();pd++){ fout<<*pd<<" "; } fout<<endl; fout<<"the finnally2 list is:"; list<string>::iterator pi; while(!four.empty()){ for(pi=four.begin();pi!=four.end();pi++) fout<<*pi<<" "; four.pop_front(); fout<<endl; } cout<<endl; fout.close(); return 1; }

    使用vector时,发现vector在使用unique()不会自动截去重复的部分,需要自己添加代码去掉重复部分,list会自动截去重复部分。

    转载请注明原文地址: https://ju.6miu.com/read-1202753.html
    最新回复(0)