在 stable_sort 函数中指定迭代器值
Specifying iterator value in stable_sort function
我正在使用以下代码对矩形进行排序。
在 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;
}
因为stable_sort
需要随机访问迭代器,你可以在迭代器上做简单的加法:
stable_sort(boundRect.begin()+5, boundRect.begin()+10, /* ... */
除非您正在处理一个古老的(C++11 之前的)编译器,否则您也可以使用 lambda 表达式进行比较:
stable_sort(boundRect.begin()+5, boundRect.begin()+10,
[](const Rect & a, const Rect &b) { return a.x < b.x; });
这不仅更短、更易于阅读,而且通常也会更快(当您只对 5 个元素进行排序时,这并不重要)。
我正在使用以下代码对矩形进行排序。 在 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;
}
因为stable_sort
需要随机访问迭代器,你可以在迭代器上做简单的加法:
stable_sort(boundRect.begin()+5, boundRect.begin()+10, /* ... */
除非您正在处理一个古老的(C++11 之前的)编译器,否则您也可以使用 lambda 表达式进行比较:
stable_sort(boundRect.begin()+5, boundRect.begin()+10,
[](const Rect & a, const Rect &b) { return a.x < b.x; });
这不仅更短、更易于阅读,而且通常也会更快(当您只对 5 个元素进行排序时,这并不重要)。