我正在用 Python 將這個資料結構重寫為 C 。用 Python 撰寫這段代碼對我來說很容易,但我在使用 C 時遇到了麻煩。我需要更改我的值中的“步驟”并通過鍵找到我的對。在 Python 中,我寫道:
step = 0
dct = {1: [step, list()]}
在c 中,我是這樣寫的,但是我找不到我的密鑰對,然后更改其中的步驟。
對模型:
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]]
}
如何從對或地圖中使用?
uj5u.com熱心網友回復:
這是一個與發布的 Python 代碼等效的粗略 C 11:
#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
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/363173.html
下一篇:根據特定值編輯字典鍵名
