2012-04-19 89 views
1

我已经矢量的矢量,如下所示:排序矢量[I] [0]

vector< vector<int> > intervals; 

基本上,我需要排序的矢量,使用STL的sort(),但我需要进行排序'间隔',间隔[i] [0]。所以,通过每个对象的[0]元素对矢量对象进行排序。

我该怎么做?先谢谢你。

+0

难道你不只是使用'map >'你的关键字是'vector [0]'吗? – EdChum 2012-04-19 19:47:33

回答

7

std::sort将对象的比较器函数作为第三个参数,因此您可以定义一个小于运算符,该运算符需要两个向量并比较它们的第一个元素。

bool foo(const std::vector<int>& a, const std::vector<int>& b) { 
    // in real life you may want to check vectors aren't empty. 
    // in real life you wouldn't call this foo either. 
    return a[0]<b[0]; 
} 

int main() { 
    std::vector<std::vector<int>> v = ...; 
    std::sort(v.begin(), v.end(), foo); 
} 
+1

我不会使用'foo'作为比较函数的名称,但除此之外,这是实现它的方法。 – 2012-04-19 19:59:05

+0

@MarkRansom我也不会!指出。 – juanchopanza 2012-04-19 20:01:18