我目前正在研究如何通过使用Q-learning算法帮助代理获得奖励来实现C ++程序。
我正在尝试使用Hashtable来存储我的状态和操作。 我不熟悉C ++编程......
我想要做的就是使用哈希表来存储数组。 但是我无法找到存储它的正确方法......哈希表称它是数组的错误类型。
using namespace std;
int state[2] = {0,0};
unordered_map<string, int> hashtable;
hashtable.emplace("State1", state);
cout << "the State of State1 is :" << hashtable["State1"] << endl; cin.get();
Error C2664 'std::pair<const _Kty,_Ty>::pair(std::pair<const _Kty,_Ty> &&)': cannot convert argument 2 from 'int [2]' to 'const int &' myproject c:\program files (x86)\microsoft visual studio
14.0 \ vc \ include \ xmemory0 737
C ++ HashTable能否将数组存储为键和值? 如果它没有任何方法将数组存储在表中?这就像Python字典函数....
谢谢!
答案 0 :(得分:2)
有一些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
答案 1 :(得分:0)
如果我做对了你想要“unordered_map&lt; string,std :: array&gt;”而不是“unordered_map&lt; string,int&gt;”。所以你的代码应该是这样的:
#include <iostream>
#include <unordered_map>
#include <string>
using namespace std;
int main() {
unordered_map<string, std::array<int,2>> hashTable = {
{"State1", {1,10}},
{"State2", {2,20}},
{"State3", {3,30}},
};
for (const auto& n : hashTable )
cout << "Key: " << n.first << "\tValue: {" << n.second[0] << ", " << n.second[1] << "}" << endl;
return 0;
}
输出将是:
Key: State3 Value: {3, 30}
Key: State1 Value: {1, 10}
Key: State2 Value: {2, 20}