Logo

Programming-Idioms

History of Idiom 100 > diff from v18 to v19

Edit summary for version 19 by :
New Cpp implementation by user [01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789]

Version 18

2016-02-18, 19:02:40

Version 19

2016-02-18, 19:14:09

Idiom #100 Sort by a comparator

Sort elements of array-like collection items, using a comparator c.

Idiom #100 Sort by a comparator

Sort elements of array-like collection items, using a comparator c.

Imports
#include <algorithm>
#include <vector>
#include <cassert>
Code
struct is_less {
    bool operator () (int a, int b){
        return a < b;
    }
};

int main(){
    std::vector<int> items = {1337, 666, -666, 0, 0, 666, -666};
    std::sort(items.begin(), items.end(), is_less());

    std::vector<int> expected = {-666, -666, 0, 0, 666, 666, 1337};
    assert(items.size() == expected.size());
    for (size_t i = 0; i < items.size(); i++){
        assert(items[i] == expected[i]);
    }
    return 0;
}
Comments bubble
c is a bad name for a comparator because it is not descriptive. is_less is a better name.

The initializer list for items requires the compiler parameter -std=c++11

std::sort might not be stable. If you want a stable sorting algorithm, use std::stable_sort instead.