Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Errors occurs when accessing unordered_map by [] operator

I stumbled upon a strange problem with an unordered_map.

First I generated an unordered_map<string, Person> and inserted a record ("Bob", Person(1, "Bob")) into the table. Then I tried to access the record by using the [] operator with key "Bob" and an error happened.

This is the code:

#include<iostream>
#include<unordered_map>
using namespace std;

class Person
{
    public:
        int play;
        string name;
        Person(int p, string n):play(p), name(n) {}
};

int main()
{
    unordered_map<string,Person> test;
    test.insert(std::make_pair("haha",Person(1,"haha")));
    cout<<test["haha"].name<<endl;
    return 0;
}

Errors occur when I compile the code with "g++ -S hash.cpp" Output:

In file included from /usr/include/c++/7/unordered_map:41:0,
                 from hash.cpp:2:
/usr/include/c++/7/tuple: In instantiation of ‘std::pair<_T1, _T2>::pair(std::tuple<_Args1 ...>&, std::tuple<_Args2 ...>&, std::_Index_tuple<_Indexes1 ...>, std::_Index_tuple<_Indexes2 ...>) [with _Args1 = {std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >&&}; long unsigned int ..._Indexes1 = {0}; _Args2 = {}; long unsigned int ..._Indexes2 = {}; _T1 = const std::__cxx11::basic_string<char>; _T2 = Person]’:
/usr/include/c++/7/tuple:1641:63:   required from ‘std::pair<_T1, _T2>::pair(std::piecewise_construct_t, std::tuple<_Args1 ...>, std::tuple<_Args2 ...>) [with _Args1 = {std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >&&}; _Args2 = {}; _T1 = const std::__cxx11::basic_string<char>; _T2 = Person]’
/usr/include/c++/7/ext/new_allocator.h:136:4:   required from ‘void __gnu_cxx::new_allocator<_Tp>::construct(_Up*, _Args&& ...) [with _Up = std::pair<const std::__cxx11::basic_string<char>, Person>; _Args = {const std::piecewise_construct_t&, std::tuple<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >&&>, std::tuple<>}; _Tp = std::pair<const std::__cxx11::basic_string<char>, Person>]’
/usr/include/c++/7/bits/alloc_traits.h:475:4:   required from ‘static void std::allocator_traits<std::allocator<_CharT> >::construct(std::allocator_traits<std::allocator<_CharT> >::allocator_type&, _Up*, _Args&& ...) [with _Up = std::pair<const std::__cxx11::basic_string<char>, Person>; _Args = {const std::piecewise_construct_t&, std::tuple<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >&&>, std::tuple<>}; _Tp = std::pair<const std::__cxx11::basic_string<char>, Person>; std::allocator_traits<std::allocator<_CharT> >::allocator_type = std::allocator<std::pair<const std::__cxx11::basic_string<char>, Person> >]’
/usr/include/c++/7/bits/hashtable_policy.h:2066:37:   required from ‘std::__detail::_Hashtable_alloc<_NodeAlloc>::__node_type* std::__detail::_Hashtable_alloc<_NodeAlloc>::_M_allocate_node(_Args&& ...) [with _Args = {const std::piecewise_construct_t&, std::tuple<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >&&>, std::tuple<>}; _NodeAlloc = std::allocator<std::__detail::_Hash_node<std::pair<const std::__cxx11::basic_string<char>, Person>, true> >; std::__detail::_Hashtable_alloc<_NodeAlloc>::__node_type = std::__detail::_Hash_node<std::pair<const std::__cxx11::basic_string<char>, Person>, true>]’
/usr/include/c++/7/bits/hashtable_policy.h:750:8:   required from ‘std::__detail::_Map_base<_Key, _Pair, _Alloc, std::__detail::_Select1st, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits, true>::mapped_type& std::__detail::_Map_base<_Key, _Pair, _Alloc, std::__detail::_Select1st, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits, true>::operator[](std::__detail::_Map_base<_Key, _Pair, _Alloc, std::__detail::_Select1st, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits, true>::key_type&&) [with _Key = std::__cxx11::basic_string<char>; _Pair = std::pair<const std::__cxx11::basic_string<char>, Person>; _Alloc = std::allocator<std::pair<const std::__cxx11::basic_string<char>, Person> >; _Equal = std::equal_to<std::__cxx11::basic_string<char> >; _H1 = std::hash<std::__cxx11::basic_string<char> >; _H2 = std::__detail::_Mod_range_hashing; _Hash = std::__detail::_Default_ranged_hash; _RehashPolicy = std::__detail::_Prime_rehash_policy; _Traits = std::__detail::_Hashtable_traits<true, false, true>; std::__detail::_Map_base<_Key, _Pair, _Alloc, std::__detail::_Select1st, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits, true>::mapped_type = Person; std::__detail::_Map_base<_Key, _Pair, _Alloc, std::__detail::_Select1st, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits, true>::key_type = std::__cxx11::basic_string<char>]’
/usr/include/c++/7/bits/unordered_map.h:980:20:   required from ‘std::unordered_map<_Key, _Tp, _Hash, _Pred, _Alloc>::mapped_type& std::unordered_map<_Key, _Tp, _Hash, _Pred, _Alloc>::operator[](std::unordered_map<_Key, _Tp, _Hash, _Pred, _Alloc>::key_type&&) [with _Key = std::__cxx11::basic_string<char>; _Tp = Person; _Hash = std::hash<std::__cxx11::basic_string<char> >; _Pred = std::equal_to<std::__cxx11::basic_string<char> >; _Alloc = std::allocator<std::pair<const std::__cxx11::basic_string<char>, Person> >; std::unordered_map<_Key, _Tp, _Hash, _Pred, _Alloc>::mapped_type = Person; std::unordered_map<_Key, _Tp, _Hash, _Pred, _Alloc>::key_type = std::__cxx11::basic_string<char>]’
hash.cpp:17:19:   required from here
/usr/include/c++/7/tuple:1652:70: error: no matching function for call to ‘Person::Person()’
         second(std::forward<_Args2>(std::get<_Indexes2>(__tuple2))...)
                                                                      ^
hash.cpp:10:3: note: candidate: Person::Person(int, std::__cxx11::string)
   Person(int p, string n):play(p), name(n) {}
   ^~~~~~
hash.cpp:10:3: note:   candidate expects 2 arguments, 0 provided
hash.cpp:5:7: note: candidate: Person::Person(const Person&)
 class Person
       ^~~~~~
hash.cpp:5:7: note:   candidate expects 1 argument, 0 provided
hash.cpp:5:7: note: candidate: Person::Person(Person&&)
hash.cpp:5:7: note:   candidate expects 1 argument, 0 provided

I had inserted the record but the map seemed to be unaware of this and tried to insert the record again.

So how does the g++ compiler process the [] operator?

Thanks.

like image 675
roland Avatar asked Sep 04 '26 17:09

roland


2 Answers

Mapped type of unordered_map must be DefaultConstructible under operator[]. I.e. Person() must have a default constructor, if you want to be able to use operator[].

As an alternative, use at():

int main() 
{ 
 std::unordered_map<string,Person> test;
 test.insert(std::make_pair("haha",Person(1,"haha")));
 std::cout<<test.at("haha").name<<'\n';
 return 0; 
}

The mapped type has to be DefaultConstructible because operator[] should be able to create missing entries. The data in new entries is default constructed .

like image 124
Michael Veksler Avatar answered Sep 06 '26 06:09

Michael Veksler


The problem is not with [] operator. Actual problem is that when the compiler executes the following line:

cout<<test["haha"].name<<endl;

It tries to create an object of type Person using it's default constructor. Since default constructor is not defined, it throws an error.

The following code will work fine. I have just added a default constructor.

#include<iostream>
#include<unordered_map>
using namespace std;

class Person
{
    public:
        int play;
        string name;
        Person(){}     //Add default constructor 
        Person(int p, string n):play(p), name(n) {}
};

int main()
{
    unordered_map<string,Person> test;
    test.insert(std::make_pair("haha",Person(1,"haha")));
    cout<<test["haha"].name<<endl;
    return 0;
}
like image 44
Krishna Choudhary Avatar answered Sep 06 '26 07:09

Krishna Choudhary



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!