James Andrews James Andrews - 2 months ago 19
C++ Question

operator [] in boost::unordered_map

So, I was reading through the documenation for boost::unordered_map at the following url:

http://www.boost.org/doc/libs/1_52_0/doc/html/boost/unordered_map.html#id1395195-bb

and it says that the effects and returns of operator[] are

Effects:
If the container does not already contain an elements with a key equivalent to k, inserts the value std::pair(k, mapped_type())

Returns:
A reference to x.second where x is the element already in the container, or the newly inserted element with a key equivalent to k

When I run the following code, it shows that the pointer to the map["xyz"] is 0. what am i missing? I see lots of people using find(key_value) but wasn't sure how this works.

#import <iostream>
#import <boost/unordered_map.hpp>

class myClass
{
public:
myClass():_i(-1){};
myClass(int i):_i(i){};
int _i;
};

int main()
{
boost::unordered_map<std::string,myClass*> map;
map["abc"] = new myClass(1);
std::cout << map["abc"] << std::endl;
std::cout << map["xyz"] << std::endl;
return 0;
}

Answer

Moving my answer from the post to the answer as Yakk suggested.

So, I solved my own problem and figure out that others might benefit from my experience or have some comments so I'm still posting.

I think that what was happening was that it was creating a new element in my map, just the rhs was a myClass*. I rewrote this as

class myClass
{
public:
    myClass():_i(-1){};
    myClass(int i):_i(i){};
    int _i;

    friend std::ostream& operator<< (std::ostream& stream, const myClass& myClass){return stream << "[" << myClass._i << "]";}
};

int main()
{
    boost::unordered_map<std::string,myClass> map;
    map["abc"] = myClass(1);
    std::cout << map["abc"] << std::endl;
    std::cout << map["xyz"] << std::endl;
    return 0;
}

and here is my output:

$ g++ test.cpp && ./a.out 
[1]
[-1]

Hope this helps someone in need.

Comments