uを助けることができるunordered_mapのヒントがいくつかあります。
#include <iostream>
#include <unordered_map>
#include <string>
#include <vector>
using namespace std;
int main() {
// constructor
unordered_map<string, int> hashTable = {
{"a", 123},
{"b", 456},
{"c", 789}
};
// update
hashTable["a"] = 1;
// add new entry
hashTable["d"] = 2;
hashTable.insert({"e", 111});
// Iterate and print keys and values of unordered_map
for (const auto& n : hashTable)
cout << "Key: " << n.first << "\tValue: " << n.second << endl;
// Output values by key
cout << "The value of d is :" << hashTable["d"] << endl;
// init vector
vector<int> states{1,2,3,4,5,6,7};
states.push_back(8);
// add vector into unordered_map
unordered_map<string, vector<int>> ht;
ht["state1"] = states;
ht.insert({"c", vector<int>{1,1,1,1}});
cout << "Values which key is 'c' in ht" << endl;
for(auto& v : ht["c"])
cout << v << "\t";
cout << endl;
/*
* put array into unordered_map
*/
int state1[3] = {0, 1, 2};
int state2[2] = {3, 4};
int state3[4] = {5, 6, 7, 8};
// declare map to store int pointer value
unordered_map<string, int*> u_map;
// add into unordered_map
u_map["a"] = state1;
u_map["b"] = state2;
u_map.insert({"c", state3});
// update
u_map["b"] = state3;
// get pointer of array
auto s1 = u_map["a"];
int* s2 = u_map["b"];
// accesses val in array
cout << "Value of key a is: "<< s2[0] << endl;
size_t size = sizeof(s1)/sizeof(s1[0]);
for (int i = 0; i <= size ; ++i) {
cout << "val " << i << " is: "<< s1[i] << endl;
}
return 0;
}
出力:
Key: d Value: 2
Key: b Value: 456
Key: c Value: 789
Key: a Value: 1
The value of d is :2
Value of key a is: 5
val 0 is: 0
val 1 is: 1
val 2 is: 2
更新:
fix use of class template 'vector' requires template arguments
update for adding array into map
。テンプレートパラメータを 'unordered_map'に変更する必要があります。 [this](http://stackoverflow.com/questions/2582529/using-array-as-map-value-cant-see-the-error)答えを参照してください。 –
あなたのハッシュテーブルの定義にある「」が何を意味しているのだろうか? –
一般的な2要素配列よりも、あなたの '状態'を表現する構造体を作る価値があるかもしれません。これにより、キー入力がより簡単になります。 – tadman