C++ algorithm like python's 'groupby'

后端 未结 6 606
再見小時候
再見小時候 2020-12-15 22:20

Are there any C++ transformations which are similar to itertools.groupby()?

Of course I could easily write my own, but I\'d prefer to leverage the idiomatic behavior

6条回答
  •  执念已碎
    2020-12-15 22:54

    Eric Niebler's ranges library provides a group_by view.

    according to the docs it is a header only library and can be included easily.

    It's supposed to go into the standard C++ space, but can be used with a recent C++11 compiler.

    minimal working example:

    #include 
    #include 
    #include 
    using namespace std;
    using namespace ranges;
    
    int main(int argc, char **argv) {
        vector l { 0,1,2,3,6,5,4,7,8,9 };
        ranges::v3::sort(l);
        auto x = l | view::group_by([](int x, int y) { return x / 5 == y / 5; });
        map> res;
    
        auto i = x.begin();
        auto e = x.end();
        for (;i != e; ++i) {
          auto first = *((*i).begin());
          res[first / 5] = to_vector(*i);
        }
    
        // res = { 0 : [0,1,2,3,4], 1: [5,6,7,8,9] }
    }
    

    (I compiled this with clang 3.9.0. and --std=c++11)

提交回复
热议问题