码迷,mamicode.com
首页 > 编程语言 > 详细

C++ sort vector<vector<int> > 容器的排序

时间:2015-09-28 11:34:47      阅读:195      评论:0      收藏:0      [点我收藏+]

标签:

 

C++的STL中提供了很强大的排序函数sort,可以对任意数组,结构体及类进行排序,下面我们先来看最简单的数组排序。默认的升序排列,我们也可以在后面加上less或greater来告诉编译器我们想要的排序顺序。

 

vector<int> v = {2, 0, 1, 5, 9, 2, 7};

// Ascending order
sort(v.begin(), v.end());
sort(v.begin(), v.end(), less<int>());

// Descending order
sort(v.rbegin(), v.rend());
sort(v.begin(), v.end(), greater<int>());

 

如果是一个二维数组,也可以是用sort,我们可以选择根据某一列来进行排序,如果我们不重写cmp函数,那么默认的是根据第一列来排序,当然我们可以通过重写来根据其他列来排序:

 

/* Input matrix
m = [
        1 4 2 
        0 8 3
        3 5 1
    ]
*/

// Ascending order by first column
sort(m.begin(), m.end());
/*
m = [
        0 8 3
        1 4 2 
        3 5 1
    ]
*/

// Descending order by first column
sort(m.rbegin(), m.rend());
/*
m = [
        3 5 1
        1 4 2 
        0 8 3
    ]
*/


// Ascending order by second column
sort(m.begin(), m.end(), [](const vector<int> &a, const vector<int> &b) { return a[1] < b[1]; } );

bool cmp(const vector<int> &a, const vector<int> &b) {
    return a[0] > b[0];
}
sort(m.begin(), m.end(), cmp);
/*
m = [
        1 4 2 
        3 5 1
        0 8 3
    ]
*/


// Descending order by second column
sort(m.begin(), m.end(), [](const vector<int> &a, const vector<int> &b) { return a[1] > b[1]; } );

bool cmp(const vector<int> &a, const vector<int> &b) {
    return a[0] < b[0];
}
sort(m.begin(), m.end(), cmp);
/*
m = [
        0 8 3
        3 5 1
        1 4 2 
    ]
*/

 

C++ sort vector<vector<int> > 容器的排序

标签:

原文地址:http://www.cnblogs.com/grandyang/p/4843528.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!