对容器元素进行排序

#include <list>
#include <vector>
#include <string>
#include <algorithm>
#include <iterator>
#include <iostream>
using namespace std;

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 ctr,const string &word, const string &ending)
{
	return (ctr==1)?word:word+ending;//make_plural(wc, "word ", "s ")当输入中文本中
	                                     //word数大于一是在word后加s,为words为word的复数!
}
int main()
{
	//words:the quick red fox jumps over the slow red turtle
	vector<string> words;
	vector<string>::iterator noUnique;
	//将单词添加入vector
	words.push_back(string("the"));
	words.push_back(string("quick"));
	words.push_back(string("red"));
	words.push_back(string("fox"));
	words.push_back(string("jumps"));
	words.push_back(string("over"));
	words.push_back(string("the"));
	words.push_back(string("slow"));
	words.push_back(string("red"));
	words.push_back(string("turtle"));

	//原样输出单词
	cout<<"before sort:"<<endl;
	cout<<"----------------------------"<<endl;
	for (vector<string>::iterator iter=words.begin();iter!=words.end();++iter)
	{
		cout << *iter<<endl;
	}
	cout<<"----------------------------"<<endl;
	//排序,然后输出
	sort(words.begin(),words.end());
	cout<<"after sort:"<<endl;
	cout<<"----------------------------"<<endl;
	for (iter=words.begin();iter!=words.end();++iter)
	{
		cout << *iter<<endl;
	}
	cout<<"----------------------------"<<endl;
	//去除重复,然后输出
	noUnique=unique(words.begin(),words.end());//将无重复的元素复制到序列的前端,返回的迭代器指向超出无重复元素范围末端的下一个位置
	words.erase(noUnique,words.end());//去除重复的元素
	cout<<"after unique:"<<endl;
	cout<<"----------------------------"<<endl;
	for (iter=words.begin();iter!=words.end();++iter)
	{
		cout << *iter<<endl;
	}
	cout<<"----------------------------"<<endl;
	//按照字符数长度排序,找出长度大于6的元素个数,并将其输出
	stable_sort(words.begin(),words.end(),isShorter);
	vector<string>::size_type wc=count_if(words.begin(),words.end(),GT6);
	cout<<wc<<" "<<make_plural(wc,"word","s")
		<<" 6 characters or longer"<<endl;
	for (iter=words.begin();iter!=words.end();++iter)
	{
		if (GT6(*iter))
		{
			cout << *iter<<endl;
		}
	}
	cout<<"----------------------------"<<endl;
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值