STL sort用法

来源:互联网 发布:java程序设计案例教程 编辑:程序博客网 时间:2024/06/10 07:00

sort函数有两个参数和三个参数的,两个参数的简单些只需起始iterator和终止iterator。

下面用一个例子说明三个参数的sort函数的用法:

如:

34        234
324      213
46        2
6          35
46        5

对第一列进行排序,第二列对应原先的数值保持不变,排序后:

6          35

34        234

46        2

46        5

324      213

程序代码:

#include <iostream>#include <vector>#include <algorithm>using namespace std;typedef struct tagTwoNum{    int x;    int y;}TWO_NUM;bool my_fun(TWO_NUM t1, TWO_NUM t2){    return (t1.x < t2.x);}int main(void){    TWO_NUM temp[] = {34, 234,                    324, 213,                    46, 2,                    6, 35,                    46, 5};    vector<TWO_NUM> vt(temp, temp+5);    vector<TWO_NUM>::iterator iter;    sort(vt.begin(), vt.end(), my_fun);    for (iter=vt.begin(); iter!=vt.end(); ++iter)    {        cout << (*iter).x << "\t" << (*iter).y << endl;    }        return 0;}



原创粉丝点击