(原創) 如何使用stable_sort() algorithm? (C/C++) (STL)
2006-12-10 02:59
609 查看
sort()和stable_sort()都對container做sort的動作,但對於相等的值,sort()和stable_sort()處理的方式不一樣,stable_sort()會保證不更改原先的順序,但sort()則不保證,有可能更改順序,但也有可能不改,這樣講還是很籠統,若用SQL來解釋,就一目暸然了。
在SQL中,我們常有以下寫法
1SELECT *
2FROM [customers]
3ORDER BY [age],[name]
我們想先依年齡排序,若年齡相同,則依姓名的字母排序
在STL我們該怎麼寫呢?
我們必須先對姓名排序,使用sort(),
然後再對年齡排序,使用stable_sort(),如此當年齡相同時,因為之前已經用姓名排序過了,stable_sort()將依照原先的排序不與改變,這樣剛好就對姓名排序了,而達到ORDER BY [age],[name]的要求。
sort()比stable_sort()速度快,若沒有stable的需求,應該考慮先使用sort()。
以下範例想先依字串長度排序,若長度相同,則依字母順序排序。
1#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
18
43a
2be
3is
4or
5to
6not
7question
在SQL中,我們常有以下寫法
1SELECT *
2FROM [customers]
3ORDER BY [age],[name]
我們想先依年齡排序,若年齡相同,則依姓名的字母排序
在STL我們該怎麼寫呢?
我們必須先對姓名排序,使用sort(),
然後再對年齡排序,使用stable_sort(),如此當年齡相同時,因為之前已經用姓名排序過了,stable_sort()將依照原先的排序不與改變,這樣剛好就對姓名排序了,而達到ORDER BY [age],[name]的要求。
sort()比stable_sort()速度快,若沒有stable的需求,應該考慮先使用sort()。
以下範例想先依字串長度排序,若長度相同,則依字母順序排序。
1#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
18
43a
2be
3is
4or
5to
6not
7question
相关文章推荐
- 如何使用stable_sort() algorithm? (C/C++) (STL)
- (原創) 如何使用unique() algorithm? (C/C++) (STL)
- (原創) 如何使用remove_copy_if() algorithm? (C/C++) (STL)
- (原創) 如何使用find_first_of() algorithm? (C/C++) (STL)
- (原創) 如何使用for_each() algorithm? (C/C++) (STL)
- (原創) 如何使用transform() algorithm? (C/C++) (STL)
- (原創) 如何使用for_each() algorithm? (C/C++) (STL)
- (原創) 如何使用remove() algorithm? (C/C++) (STL)
- (原創) 如何使用find() algorithm? (C/C++) (STL)
- 使用STL中的stable_sort()函数进行排序
- (原創) 如何将array转成std::vector? (使用vector.insert) (C/C++) (STL)
- (原創) 如何使用C++的標準函式庫進行排序? (C/C++) (STL)
- (原創) 如何使用STL寫XML轉檔程式? (C/C++) (STL) (Web) (XML)
- 如何使用unique() algorithm? (C/C++) (STL)
- (原創) 如何使用multimap? 如何使用StringStream解析文字檔? (C/C++) (STL)
- (原創) 如何使用reverse_iterator? (C/C++) (STL)
- (原創) 如何使用queue? (C/C++) (STL)
- 如何使用remove_copy_if() algorithm? (C/C++) (STL)
- (原創) 如何将array转成std::vector? (使用constructor) (C/C++) (STL)
- (原創) 如何使用Function Object? (C/C++) (STL)