您的位置:首页 > 产品设计 > UI/UE

泛型算法——容器元素的排序算法(统计长度不小于6的单词个数)sort unique stable_sort count_if

2007-03-09 11:07 302 查看
#include <iostream>
#include <conio.h>
#include <string>
#include <vector>
#include <list>
#include <algorithm>
#include <numeric>
using namespace std;

// 打印容器内容
void printVec(const vector<string> &vecT)
{
 vector<string>::const_iterator vecIt= vecT.begin();
 for (; vecIt != vecT.end(); vecIt ++)
 {
  cout<<*vecIt<<endl;
 }
 cout<<endl;
}
void iniVec( vector<string> &vecT)
{
 vecT.erase(vecT.begin(),vecT.end());
 char ch = 'a';
 string strT = "";
 for (int i=0;i<10;i++)
 {
  vecT.push_back(strT+ch++);
 }
}
void printList(const list<string> &listT)
{
 list<string>::const_iterator listIt= listT.begin();
 for (; listIt != listT.end(); listIt ++)
 {
  cout<<*listIt<<endl;
 }
 cout<<endl;
}

bool isShorter(const string &s1,const string &s2)
{
 return s1.size() < s2.size();
}
bool GT6(const string &s)
{
 return s.size()>=6;
}
string make_plural(size_t st,const string &s1,const string &s2)

 return st>1 ? s1+s2 : s1;
}
int main()
{
    cout<<"以下是容器元素的排序算法(统计长度不小于6的单词个数)"<<endl;
 
 vector<string> vecTest;
 string next_word;
 while(cin>>next_word)
 {
  vecTest.push_back(next_word);
  if(vecTest.size()>3 )
          break;
 }
 printVec(vecTest);
 sort(vecTest.begin(),vecTest.end());
 printVec(vecTest);

 vector<string>::iterator end_unique =
  unique(vecTest.begin(),vecTest.end());
 vecTest.erase(end_unique , vecTest.end());

 stable_sort(vecTest.begin(),vecTest.end(),isShorter);
 printVec(vecTest);

 vector<string>::size_type wc =
  count_if(vecTest.begin() , vecTest.end(),GT6);

 cout<<wc <<" "<<make_plural(wc,"word","s")
  << " 6 characters or longer"<<endl;
 
 

 getch();
 return 0;
}
 输出
以下是容器元素的排序算法(统计长度不小于6的单词个数)
sdfadfdfsa
asdfasdf
asdfasd
as
sdfadfdfsa
asdfasdf
asdfasd
as

as
asdfasd
asdfasdf
sdfadfdfsa

as
asdfasd
asdfasdf
sdfadfdfsa

3 words 6 characters or longer
 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐