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

/**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会自动截去重复部分。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值