STL算法 -------- 对所有元素排序

1. sort( b, e)

2. sort( b, e, p )

3. stable_sort( b, e )

4. stable_sort( b, e, p )

注意:

         不适用于list容器,list有成员函数sort

#include <iostream>
#include <algorithm>
#include <vector>
#include <list>
#include <deque>
#include <functional>

using namespace std;

template<typename T>
void Print(const T& t)
{
	for(typename T::const_iterator itr=t.begin(); itr!=t.end(); ++itr)
	{
		cout<<*itr<<' ';
	}cout<<endl;
}

int main( int argc, char** argv )
{
	deque<int> deq;

	for(int i=1; i<=9; ++i)
	{
		deq.push_back(i);
	}
	for(int i=1; i<=9; ++i)
	{
		deq.push_back(i);
	}
	Print(deq);

	sort(deq.begin(), deq.end());
	Print(deq);
	sort(deq.begin(), deq.end(), greater<int>());
	Print(deq);


	return 0;
}

#include <iostream>
#include <algorithm>
#include <vector>
#include <list>
#include <deque>
#include <functional>
#include <string>

using namespace std;

template<typename T>
void Print(const T& t)
{
	for(typename T::const_iterator itr=t.begin(); itr!=t.end(); ++itr)
	{
		cout<<*itr<<' ';
	}cout<<endl;
}

bool lessLength(const string& s1, const string& s2)
{
	return s1.length()<s2.length();
}

int main( int argc, char** argv )
{
	vector<string> vec;
	vector<string> vec2;

	vec.push_back("1xxx");
	vec.push_back("2x");
	vec.push_back("3x");
	vec.push_back("4x");
	vec.push_back("5xx");
	vec.push_back("6xxxx");
	vec.push_back("8xxx");
	vec.push_back("9xx");
	vec.push_back("10xxx");
	vec.push_back("11");
	vec.push_back("12");
	vec.push_back("13");
	vec.push_back("14xx");
	vec.push_back("15");
	vec.push_back("16");
	vec.push_back("17");
	vec2 = vec;
	Print(vec);
	sort(vec.begin(), vec.end(), lessLength);
	Print(vec);
	cout<<endl<<"vec2:"<<endl;
	stable_sort(vec2.begin(), vec2.end(), lessLength);
	Print(vec2);

	return 0;
}


posted @ 2015-03-10 14:07  SandKing  阅读(4)  评论(0)    收藏  举报  来源