Search code examples
c++11stable-sort

Specifying iterator value in stable_sort function


I am using the below code to sort rectangles. In the stable_sort function, how can I specify the iterator values other than boundRect.begin and boundRect.end. I want to sort the elements between index 5 to 10. How can I specify these in the stable_sort function? Please guide me.

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

Solution

  • Since stable_sort requires random access iterators, you can do simple addition on the iterators:

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

    Unless you're dealing with an ancient (pre-C++11) compiler, you can use a lambda expression for the comparison as well:

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

    This not only shorter and easier to read, but will often be faster as well (not that it's likely to matter when you're only sorting 5 elements).