在stable_sort函数中指定迭代器值

时间:2015-02-16 19:16:20

标签: c++11 stable-sort

我使用以下代码对矩形进行排序。 在stable_sort函数中,如何指定除boundRect.begin和boundRect.end之外的迭代器值。我想对索引5到10之间的元素进行排序。如何在stable_sort函数中指定它们?请指导我。

stable_sort( boundRect.begin(), boundRect.end(), compareX_rect );
bool compareX_rect(const Rect & a, const Rect &b) {
    return a.x <= b.x;
}

1 个答案:

答案 0 :(得分:4)

由于stable_sort需要随机访问迭代器,因此可以对迭代器进行简单的添加:

stable_sort(boundRect.begin()+5, boundRect.begin()+10, /* ... */

除非你正在处理一个古老的(pre-C ++ 11)编译器,否则你也可以使用lambda表达式进行比较:

stable_sort(boundRect.begin()+5, boundRect.begin()+10, 
    [](const Rect & a, const Rect &b) { return a.x < b.x; });

这不仅更短,更容易阅读,而且通常也会更快(当你只排序5个元素时,并不重要)。