笔试阿里的时候搞到我了,一直想着对list用之前的sort排序,结果一直报错。。。
(1)vector的迭代器是随机访问迭代器,支持泛型算法的sort及其算法。可以使用STL中的sort。
//vector排序
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <numeric>
using namespace std;
//两个谓词函数
bool isShorter(const string &pre,const string &cur)
{
return (pre.size()<cur.size());
}
bool GT4(const string &str)
{
return (str.size()>=4);
}
int main()
{
cout<<"输入几个单词:"<<endl;
string str;
vector<string> strVec;
while (getline(cin,str))
{
if(str.size()==0)
break;
strVec.push_back(str);
}
//字典序
sort(strVec.begin(),strVec.end());
//去除重复的单词,返回一个迭代器,表示无重复的值得范围的结束
vector<string>::iterator iter_unique = unique(strVec.begin(),strVec.end());
//去除容器末尾重复的单词
strVec.erase(iter_unique,strVec.end());
sort(strVec.begin(),strVec.end(),isShorter);//按字符长短排序,相同长度的按字典序
cout<<"排序后的单词:"<<endl;
vector<string>::iterator iter = strVec.begin();
while (iter!=strVec.end())
{
cout << *iter<<"\t";
++iter;
}
cout<<endl;
vector<string>::size_type cnt = count_if(strVec.begin(),strVec.end(),GT4);
cout<<cnt<<"个单词的长度大于等于4。"<<endl;
system("pause");
return 0;
}
其中unique函数返回一个迭代器,unique后需要调用erase手动删除容器尾部重复的单词。
(2)而list容器上的迭代器是双向的,不支持随机访问,因此不能使用需要随机访问迭代器的sort算法。C++为list容器提供了特有的算法。
//list排序
#include <iostream>
#include <string>
#include <list>
#include <algorithm>
#include <numeric>
using namespace std;
bool isShorter(const string &pre,const string &cur)
{
return (pre.size()<cur.size());
}
bool GT4(const string &str)
{
return (str.size()>=4);
}
int main()
{
cout<<"输入几个单词:"<<endl;
string str;
list<string> strList;
while (getline(cin,str))
{
if(str.size()==0)
break;
strList.push_back(str);
}
strList.sort();//字典序
strList.unique();//去除重复的单词
strList.sort(isShorter);//按字符长短排序,相同长度的按字典序
cout<<"排序后的单词:"<<endl;
list<string>::iterator iter = strList.begin();
while (iter!=strList.end())
{
cout << *iter<<"\t";
++iter;
}
cout<<endl;
list<string>::size_type cnt = count_if(strList.begin(),strList.end(),GT4);
cout<<cnt<<"个单词的长度大于等于4。"<<endl;
system("pause");
return 0;
}