当前位置: 代码迷 >> 综合 >> 泛型算法——容器元素的排序算法(统计长度不小于6的单词个数)sort unique stable_sort count_if
  详细解决方案

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

热度:27   发布时间:2023-12-07 23:45:12.0

#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
 

  相关解决方案