我有一个地图,其结构定义如下:
struct kv_string {
std::string value;
long long exp_time;
kv_string(const std::string& v): value(v), exp_time(-1) {}
};
现在,当我尝试使用插入新结构时
else if(qargs[0] == "set"){
if(qargs.size()==3){
kv_map.insert(std::make_pair( qargs[1], kv_string(qargs[2])));
}
}
(qargs是
vector<string>
),出现以下错误:> In file included from /usr/include/c++/4.8/map:61:0,
> from structures.h:5:
> /usr/include/c++/4.8/bits/stl_map.h: In instantiation of ‘std::map<_Key, _Tp, _Compare, _Alloc>::mapped_type& std::map<_Key,
> _Tp, _Compare, _Alloc>::operator[](const key_type&) [with _Key = std::basic_string<char>; _Tp = kv_string; _Compare =
> std::less<std::basic_string<char> >; _Alloc =
> std::allocator<std::pair<const std::basic_string<char>, kv_string> >;
> std::map<_Key, _Tp, _Compare, _Alloc>::mapped_type = kv_string;
> std::map<_Key, _Tp, _Compare, _Alloc>::key_type =
> std::basic_string<char>]’:
> /usr/include/c++/4.8/stdexcept:281:48: required from here
> /usr/include/c++/4.8/bits/stl_map.h:469:59: error: no matching function for call to ‘kv_string::kv_string()’
> __i = insert(__i, value_type(__k, mapped_type()));
> ^
> /usr/include/c++/4.8/bits/stl_map.h:469:59: note: candidates are:
> structures.h:11:9: note: kv_string::kv_string(const string&)
> kv_string(const std::string& v): value(v), exp_time(-1) {}
> ^
> structures.h:11:9: note: candidate expects 1 argument, 0 provided
> structures.h:8:8: note: kv_string::kv_string(const kv_string&)
> struct kv_string {
> ^
> structures.h:8:8: note: candidate expects 1 argument, 0 provided
> make: *** [server_main.o] Error 1
我还尝试添加其他构造函数
kv_string(){}
,但它给出了分段错误。 最佳答案
你要这个:
kv_map.insert(std::make_pair(qargs[1], kv_string(qargs[2]));
或这个:
kv_map.emplace(qargs[1], kv_string(qargs[2]);
或者,在C ++ 17中:
kv_map.try_emplace(qargs[1], qargs[2]);
[]
操作符默认初始化一个新元素(如果给定键不存在),但是您的类型kv_string
不可默认构造。因此,您不能使用该运算符。上面的操作也比[]
操作符更强大:它们将迭代器返回给键处的元素,并提供有关键是否已存在的信息。关于c++ - 插入map <string,STRUCT>错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36303556/