2017-07-19 60 views
-1

我想要做的是基本上有一个关键值存储在一个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));

+0

您可能需要包含实用程序标题。 –

+0

你为什么使用'new'?管理员经理遇到了什么问题; mgr.add(...);'? – Praetorian

+1

如何使用[]运算符。 void add(const std :: string&name,unsigned int val){map {name] = val; } –

回答

2

std::make_pair签名是错误的。应该是:

map.insert(std::make_pair(name, val));