I am re-writing this data structure in Python to c . Writing this code in Python is easy for me, but I have trouble with C . I need to change the "step" in my value and find my pairs through the keys. In Python, I wrote:
step = 0
dct = {1: [step, list()]}
In c , I write like this, but I can not find my pairs with the key and then change the step in them.
pair model:
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] << "]]}";
output:
dict = {1: [3, [10]]}
and my goal is to make such a thing with loop:
{
1: [0, []],
2: [0, []],
3: [0, []],
4: [0, []]
}
That I can later call with the key and change my list, like this:
{
1: [1, [5, 1]],
2: [2, [1, 1]],
3: [0, [1, 2, 3, 4]],
4: [0, [1, 17]]
}
How can I use from pair or map?
CodePudding user response:
Here's a rough C 11 equivalent to the posted Python code:
#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;
}
When I run it, I see output like this:
Key=1
value=7 / 3 8 0 2 4
Key=2
value=78 / 9 0 5 2
Key=3
value=42 / 3 7 9