程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> 對容器元素進行排序

對容器元素進行排序

編輯:C++入門知識

#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;
}

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved