如何将 dct = {int : [int, list()]] 从 Python 转换为 C++?

how convert dct = {int : [int, list()]] from Python to C++?

我正在将Python中的这个数据结构重写为c++。 在 Python 中编写这段代码对我来说很容易,但我对 C++ 有困难。 我需要更改值中的“步骤”并通过键找到我的对。 在Python中,我写道:

step = 0
dct = {1: [step, list()]}

在c++中,我是这样写的,但是我找不到我的pairs和key,然后改变其中的step。

配对模型:

pair<int, pair<int, deque<int>>> p_p;

p_p.first = 1;
p_p.second.first = 3;
p_p.second.second.push_back(10);

cout << "dict = {" << p_p.first << ": [" << p_p.second.first << ", [" << p_p.second.second[0] << "]]}";

输出:

dict = {1: [3, [10]]}

我的目标是用循环做这样的事情:

{
 1: [0, []],
 2: [0, []],
 3: [0, []],
 4: [0, []]
}

稍后我可以使用密钥调用并更改我的列表,如下所示:

{
1: [1, [5, 1]],
2: [2, [1, 1]],
3: [0, [1, 2, 3, 4]],
4: [0, [1, 17]]
}

如何使用 pair 或 map?

这里有一个粗略的 C++11 等效于发布的 Python 代码:

#include <iostream>
#include <map>
#include <utility>  // for std::pair
#include <vector>

int main(int argc, char ** argv)
{
   std::map<int, std::pair<int, std::vector<int> > > dct;

   int step = 0;

   // insert some empty pairs into (dct)
   for (int i=1; i<4; i++) dct[i] = std::pair<int, std::vector<int> >();

   // add some random data to each entry in (dct)
   for (auto & e : dct)
   {
      const int & key = e.first;
      std::pair<int, std::vector<int> > & value = e.second;

      int & iVal = value.first;
      iVal = rand()%100;  // set the first value of the pair to something

      std::vector<int> & vec = value.second;
      for (int j=rand()%5; j>=0; j--) vec.push_back(rand()%10);
   }

   // Finally, we'll iterate over (dct) to print out its contents
   for (const auto & e : dct)
   {
      const int & key = e.first;
      std::cout << "Key=" << key << std::endl;

      const std::pair<int, std::vector<int> > & value = e.second;
      std::cout << "  value=" << value.first << " /";
      for (auto i: value.second) std::cout << " " << i;
      std::cout << std::endl;
   }

   return 0;
}

当我 运行 它时,我看到这样的输出:

Key=1
  value=7 / 3 8 0 2 4
Key=2
  value=78 / 9 0 5 2
Key=3
  value=42 / 3 7 9