注意:不可用对list或forward list调用这些算法,因为两者都不提供随机访问迭代器.不过你可以使用它们的成员函数sort()来进行排序
sort()保证了很不错的平均效能nlogn
使用例子:
template<typename T>
inline void INSERT_ELEMENTS(T& coll, int first, int last)
{
for (int i = first; i <= last; ++i)
{
coll.insert(coll.end(), i);
}
}
template<typename T>
inline void PRINT_ELEMENTS(const T & coll, const string& optcstr = "")
{
cout << optcstr;
for (auto elem : coll)
{
cout << elem << ' ';
}
cout << endl;
}
int main()
{
deque<int>a;
INSERT_ELEMENTS(a, 1, 9);
INSERT_ELEMENTS(a, 1, 9);
PRINT_ELEMENTS(a, "a: ");
sort(a.begin(), a.end());
PRINT_ELEMENTS(a, "a: ");
sort(a.begin(), a.end(), greater<int>());
PRINT_ELEMENTS(a, "sorted>: ");
}
使用stable_sort:
template<typename T>
inline void PRINT_ELEMENTS(const T & coll, const string& optcstr = "")
{
cout << optcstr;
for (auto elem : coll)
{
cout << elem << ' ';
}
cout << endl;
}
bool lessLength(const string & s1, const string &s2)
{
return s1.length() < s2.length();
}
int main()
{
vector<string>a = { "1xxx","2x","3x","4x","5xx","6xxxx","7xx","8xxx","9xx",
"10xxx","11","12","13","14xx","15","16","17" };
vector<string>b(a);
PRINT_ELEMENTS(a, "on entry:\n");
sort(a.begin(), a.end(), lessLength);
stable_sort(b.begin(), b.end(), lessLength);
PRINT_ELEMENTS(a, "\nsort: \n");
PRINT_ELEMENTS(b, "\nstable_sort: \n");
}