c++ - 插入 map<string, STRUCT> 错误

标签 c++ dictionary stl

我有一个结构定义如下的 map :

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]);

[]-operator default-initializes 一个新元素(如果给定键不存在),但是你的类型 kv_string 不可默认构造。所以你不能使用那个运算符。上述操作也比 [] 运算符更强大:它们返回指向键处元素的迭代器,以及有关键是否已存在的信息。

关于c++ - 插入 map<string, STRUCT> 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36303556/

相关文章:

c++ - TypeId 未按预期打印信息

c++ - "type-switch"在 C++11 中构造

c# - 字典键存在时找不到

python - 在python中匹配两个字典(交叉匹配)

c++ - 保留插入顺序但不允许重复的 STL 容器

c++ - 哪个更快 : STL queue or STL stack?

c++ - Qt 4.8 : trying to sort QList<QStringList> on 1st element of QStringList as integer

c++ - 是否有带有 DEBUG dll 的 VC++ 2008 Redistributable Package 版本?

python - 迭代 python 字典的键,当键是整数时,我得到这个错误, "TypeError: argument of type ' int' 不可迭代”

C++ 自定义比较器不工作 MWE