2

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?

Angus Comber
  • 9,316
  • 14
  • 59
  • 107
  • To my knowledge this is not possible, but you could use a pointer-type for the value and assign `NULL` or `nullptr` if no value is supposed to be present. –  May 22 '16 at 11:59

1 Answers1

5

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"];
juanchopanza
  • 223,364
  • 34
  • 402
  • 480