私がしようとしているのは、キーで値を参照できるように、基本的にC++クラスのキー値ストアを持つことです。私はこのようなコードでunordered_mapを使用しようとしています。 (私はそれを少し単純化しましたが、あなたはそのアイデアを得ます)。unordered_mapに挿入する際の型変換の問題
#include <string>
#include <unordered_map>
#include <iostream>
class manager
{
public:
manager() {}
~manager(){}
void add(const std::string& name, unsigned int val) {
map.insert(std::make_pair<std::string, unsigned int>(name, val));
}
unsigned int GetValue(const std::string& key) {
return map[key];
}
std::unordered_map<std::string, unsigned int> map;
};
int main(void)
{
manager* mgr = new manager();
mgr->add("Bob",22);
std::cout << "Bob is" << mgr->GetValue("Bob") << std::endl;
return 0;
}
私はちょうど私が簡単に名前で値を検索し、簡単にメモリリークを避けるために行わときにそれをクリーンアップすることができますように名前と値を格納したいです。私は、Linux(G ++ -oテストTEST.CPP)でこれをコンパイル
私は、次を得る:
test.cpp: In member function ‘void manager::add(const string&, unsigned int)’: test.cpp:12:65: error: no matching function for call to ‘make_pair(const string&, unsigned int&)’
map.insert(std::make_pair(name, val)); ^In file included from /usr/include/c++/6/bits/stl_algobase.h:64:0, from /usr/include/c++/6/bits/char_traits.h:39, from /usr/include/c++/6/string:40, from test.cpp:1: /usr/include/c++/6/bits/stl_pair.h:497:5: note: candidate: template constexpr std::pair::__type, typename std::__decay_and_strip<_T2>::__type> std::make_pair(_T1&&, _T2&&) make_pair(_T1&& __x, _T2&& __y) ^~~~~~~~~ /usr/include/c++/6/bits/stl_pair.h:497:5: note: template argument deduction/substitution failed: test.cpp:12:56: note: cannot convert ‘name’ (type ‘const string {aka const std::__cxx11::basic_string}’) to type ‘std::__cxx11::basic_string&&’
map.insert(std::make_pair(name, val));
ユーティリティヘッダーが必要な場合があります。 –
なぜあなたは 'new'を使っていますか? 'マネージャーmgrの何が問題なの? mgr.add(...); '? – Praetorian
[]演算子の使い方はどうですか? void add(const std :: string&name、unsigned int val){ map [name] = val; } –