首页 > 解决方案 > c++中unordered_map的高效笛卡尔积

问题描述

我使用 itertools.product() 在 python 中生成多个字典列表的产品。

现在我正在尝试在 C++ 中实现基本的笛卡尔积,但生成产品需要很多时间。您能给我一些建议以提高效率吗?谢谢你。

vector<vector<unordered_map<string, string>>> iter_product(\
                vector<vector<unordered_map<string, string>>> &maps_list){

  vector<vector<unordered_map<string, string>>> out;
  for (auto map = maps_list[0].begin(); map != maps_list[0].end(); map++){
    out.push_back(vector<unordered_map<string, string>>({*map}));
  }
  if (maps_list.size() > 1){
    for (int i = 1; i < maps_list.size(); i++){
      vector<vector<unordered_map<string, string>>> new_out;
      for (int j = 0; j < out.size(); j++){
        for (int k = 0; k < maps_list[i].size(); k++){
          out[j].push_back(maps_list[i][k]);
          new_out.push_back(out[j]);
        }
      }
      out = new_out;
    }
  }
  return out;
}

标签: c++cartesian-product

解决方案


如上所述,我还认为您应该使用引用作为参数,而不是实际的向量。此外,如果知道,您可以预定义矢量大小。


推荐阅读