简体   繁体   中英

How to insert a key but no value into a std::unordered_map

I have a

std::unordered_map< std::string, std::unordered_map<std::string, std::string> > 

and I want to just insert the key and fill up the values later.

eg like this:

#include <string>
#include <unordered_map>

int main() {
    std::unordered_map< std::string, std::unordered_map<std::string, std::string> > mymap;
    mymap.insert("TestKey");
}

Which gives error:

source.cpp(6): error C2664: 'void std::_Hash<std::_Umap_traits<_Kty,_Ty,std::_Uhash_compare<_Kty,_Hasher,_Keyeq>,_Alloc,false>>::insert(std::initializer_list<std::pair<const _Kty,_Ty>>)' : cannot convert argument 1 from 'const char [8]' to 'std::pair<const _Kty,_Ty> &&'
1>          with
1>          [
1>              _Kty=std::string
1>  ,            _Ty=std::unordered_map<std::string,std::string,std::hash<std::string>,std::equal_to<std::string>,std::allocator<std::pair<const std::string,std::string>>>
1>  ,            _Hasher=std::hash<std::string>
1>  ,            _Keyeq=std::equal_to<std::string>
1>  ,            _Alloc=std::allocator<std::pair<const std::string,std::unordered_map<std::string,std::string,std::hash<std::string>,std::equal_to<std::string>,std::allocator<std::pair<const std::string,std::string>>>>>
1>          ]
1>          and
1>          [
1>              _Kty=std::string
1>  ,            _Ty=std::unordered_map<std::string,std::string,std::hash<std::string>,std::equal_to<std::string>,std::allocator<std::pair<const std::string,std::string>>>
1>          ]
1>          Reason: cannot convert from 'const char [8]' to 'std::pair<const _Kty,_Ty>'
1>          with
1>          [
1>              _Kty=std::string
1>  ,            _Ty=std::unordered_map<std::string,std::string,std::hash<std::string>,std::equal_to<std::string>,std::allocator<std::pair<const std::string,std::string>>>
1>          ]
1>          No constructor could take the source type, or constructor overload resolution was ambiguous

How can I add the key with no values?

operator[] will insert a value-initialized value if an element with the given key doesn't already exist. So you can simply do this:

mymap["TestKey"];

If you want to get a reference to the value, then

auto& val = mymap["TestKey"];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM