C++ algorithm like python's 'groupby'

后端 未结 6 602
再見小時候
再見小時候 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:51

    I wrote a C++ library to address this problem in an elegant way. Given your struct

    struct foo
    {
        int x;
        std::string y;
        float z;
    };
    

    To group by y you simply do:

    std::vector dataframe;
    ...
    auto groups = group_by(dataframe, &foo::y);
    

    You can also group by more than one variable:

    auto groups = group_by(dataframe, &foo::y, &foo::x);
    

    And then iterate through the groups normally:

    for(auto& [key, group]: groups)
    {
        // do something
    }
    

    It also has other operations such as: subset, concat, and others.

提交回复
热议问题