[英]Issue inserting into stl::map
I am trying to create a <function name, function ptr>
pair using std::map
我正在尝试使用
std::map
创建一个<function name, function ptr>
对
typedef int(*FnPtr)()
int Foo()
{
return 1;
}
map<const char*, FnPtr> funcMap;
funcMap.insert("Foo", Foo); // Error
I get the following error message: 我收到以下错误消息:
Error: no instance of overloaded function "std:map<_Kty, _Ty, _Pr, _Alloc>::insert[with _Kty=const char*, _Ty=FnPtr,_Pr=std::less < const char * > , _Alloc=std::allocator< std::pair< const char* const, FnPtr>>]" matches the argument list
argument types are: (const char[3], void())
object type is: 对象类型是:
std::map< const char*, FnPtr, std::less < const char *>, std::allocator< std::pair < const char* const, FnPtr>>>
Does std:map
not support custom types? std:map
不支持自定义类型吗?
map::insert
takes an std::pair
as argument, so you need map::insert
将std::pair
作为参数,因此您需要
funcMap.insert(std::make_pair("Foo", Foo));
This will fix the compilation error, but, assuming you care about the ordering of elements, it's unlikely your map
will behave as you expect it to. 这将解决编译错误,但是,假设您关心元素的排序,则
map
不太可能像您期望的那样运行。 As defined, your keys are going to have arbitrary ordering depending upon the address that the string literals happen to be placed in memory by the compiler because the map comparator is going to compare addresses of the string literals, and not their contents. 按照定义,您的键将具有任意顺序,具体取决于编译器恰好将字符串文字放入内存的地址,因为映射比较器将比较字符串文字的地址,而不是其内容。
If you want the keys to be ordered by the string contents, then the easiest way is to change the map
to 如果要按字符串内容对键进行排序,那么最简单的方法是将
map
更改为
std::map<std::string, FnPtr> funcMap;
If you want to avoid using std::string
, and work with string literals only, then you can define a custom comparator for comparing the strings 如果要避免使用
std::string
,而仅使用字符串文字,则可以定义一个自定义比较器来比较字符串
#include <cstring>
struct str_literal_less
{
bool operator()(char const *l, char const *r) const
{ return std::strcmp(l, r) < 0; }
};
Then define the map as 然后将地图定义为
std::map<char const *, FnPtr, str_literal_less> funcMap;
You have to insert a pair into a map. 您必须在地图中插入一对。 Try:
尝试:
funcMap.insert(make_pair("Foo", Foo));
If you have C++11 support, you can do 如果您有C ++ 11支持,则可以
funcMap.insert({"Foo", Foo});
Alternatively, why can't you just do this? 或者,为什么您不能这样做呢?
funcMap["Foo"] = Foo;
You have to change 你必须改变
funcMap.insert("Foo", Foo);
In 在
funcMap.insert(make_pair("Foo", Foo));
For more info you can read here http://www.cplusplus.com/reference/map/map/insert/ 有关更多信息,您可以在这里阅读http://www.cplusplus.com/reference/map/map/insert/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.