是否有任何类似于 itertools.groupby()
的 C++ 转换?
当然,我可以轻松地编写自己的代码,但我更喜欢利用惯用行为或从 STL 或 boost
提供的功能中组合一个。
#include <cstdlib>
#include <map>
#include <algorithm>
#include <string>
#include <vector>
struct foo
{
int x;
std::string y;
float z;
};
bool lt_by_x(const foo &a, const foo &b)
{
return a.x < b.x;
}
void list_by_x(const std::vector<foo> &foos, std::map<int, std::vector<foo> > &foos_by_x)
{
/* ideas..? */
}
int main(int argc, const char *argv[])
{
std::vector<foo> foos;
std::map<int, std::vector<foo> > foos_by_x;
std::vector<foo> sorted_foos;
std::sort(foos.begin(), foos.end(), lt_by_x);
list_by_x(sorted_foos, foos_by_x);
return EXIT_SUCCESS;
}
原文由 Brian Cain 发布,翻译遵循 CC BY-SA 4.0 许可协议
用一行代码的算法来膨胀标准 C++ 库有什么意义?
另外,看看
std::multimap
,它可能正是您所需要的。更新:
当你的向量已经排序时,我提供的单行没有很好地优化。如果我们记住先前插入对象的迭代器,则可以减少许多映射查找,因此它是下一个对象的“键”,并且仅在键更改时才进行查找。例如: