如何使用stable_sort() algorithm? (C/C++) (STL)
时间:2010-10-27 来源:李sir
在SQL中,我們常有以下寫法
1SELECT *
2FROM [customers]
3ORDER BY [age],[name]
2FROM [customers]
3ORDER BY [age],[name]
我們想先依年齡排序,若年齡相同,則依姓名的字母排序
在STL我們該怎麼寫呢?
我們必須先對姓名排序,使用sort(),
然後再對年齡排序,使用stable_sort(),如此當年齡相同時,因為之前已經用姓名排序過了,stable_sort()將依照原先的排序不與改變,這樣剛好就對姓名排序了,而達到ORDER BY [age],[name]的要求。
sort()比stable_sort()速度快,若沒有stable的需求,應該考慮先使用sort()。
以下範例想先依字串長度排序,若長度相同,則依字母順序排序。
1/**//*
2(C) OOMusou 2006 http://oomusou.cnblogs.com
3
4Filename : GenericAlgo_stable_sort.cpp
5Compiler : Visual C++ 8.0 / ISO C++
6Description : Demo how to use stable_sort() algorithm
7Release : 12/10/2006
8*/
9#include <iostream>
10#include <algorithm>
11#include <string>
12#include <sstream>
13#include <vector>
14
15using namespace std;
16bool sortRule(const string&, const string&);
17
18int main() {
19 string s = "to be or not to be is a question";
20 // Transfer string to stringstream
21 istringstream ss(s);
22
23 // Copy stringstream to vector
24 vector<string> svec;
25 copy(istream_iterator<string>(ss), istream_iterator<string>(), back_inserter(svec));
26
27 // Sort vector by alphabetic order for unique() algorithm
28 sort(svec.begin(), svec.end());
29
30 // Unique vector
31 vector<string>::iterator iter = unique(svec.begin(),svec.end());
32 svec.erase(iter, svec.end());
33
34 // Stable sort vector by size
35 stable_sort(svec.begin(), svec.end(), sortRule);
36
37 // Copy vector to cout
38 copy(svec.begin(), svec.end(), ostream_iterator<string>(cout, "\n"));
39
40 return 0;
41}
42
43bool sortRule(const string& s1, const string& s2) {
44 return s1.size() < s2.size();
45}
2(C) OOMusou 2006 http://oomusou.cnblogs.com
3
4Filename : GenericAlgo_stable_sort.cpp
5Compiler : Visual C++ 8.0 / ISO C++
6Description : Demo how to use stable_sort() algorithm
7Release : 12/10/2006
8*/
9#include <iostream>
10#include <algorithm>
11#include <string>
12#include <sstream>
13#include <vector>
14
15using namespace std;
16bool sortRule(const string&, const string&);
17
18int main() {
19 string s = "to be or not to be is a question";
20 // Transfer string to stringstream
21 istringstream ss(s);
22
23 // Copy stringstream to vector
24 vector<string> svec;
25 copy(istream_iterator<string>(ss), istream_iterator<string>(), back_inserter(svec));
26
27 // Sort vector by alphabetic order for unique() algorithm
28 sort(svec.begin(), svec.end());
29
30 // Unique vector
31 vector<string>::iterator iter = unique(svec.begin(),svec.end());
32 svec.erase(iter, svec.end());
33
34 // Stable sort vector by size
35 stable_sort(svec.begin(), svec.end(), sortRule);
36
37 // Copy vector to cout
38 copy(svec.begin(), svec.end(), ostream_iterator<string>(cout, "\n"));
39
40 return 0;
41}
42
43bool sortRule(const string& s1, const string& s2) {
44 return s1.size() < s2.size();
45}
執行結果
1a
2be
3is
4or
5to
6not
7question
2be
3is
4or
5to
6not
7question
相关阅读 更多 +