Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::map of objects or object pointers?

Tags:

c++

find

class

map

I have two options to create a std map. I can work with both the types of map.

1.    std::map<A, std::string>    
2.    std::map<A*, std::string>

where A is a class object

Later in the code I will have to perform a find operation.

1.    std::map<A, std::string>   myMap1;
          if(myMap1.find(A_obj) != myMap1.end())
          {
          }

2.    std::map<A*, std::string>   myMap2;
          if(myMap2.find(A_obj_ptr) != myMap2.end())
          {
          }

I want to know which one is recommend to create. In which of these two, would I not have to overload any operators in class A for find operation to work. Which of these would have problems on insert operation when any operators are not overloaded.

If it helps, this is class A

class A
{
    private:
        std::vector<std::string> m_member;

    public:
        A(std::vector<std::string> input);  
};
like image 933
ontherocks Avatar asked Feb 11 '14 18:02

ontherocks


People also ask

Can I use a pointer as a key map?

One possible downside to using pointers as keys in maps is that the order of the items is non-deterministic (depends on their memory address). If you need to iterate over the items in a deterministic order, you can't use pointers as keys. This can be important in multiplayer games.

When would you use pointers to objects?

Pointers are used extensively in both C and C++ for three main purposes: to allocate new objects on the heap, to pass functions to other functions. to iterate over elements in arrays or other data structures.

What is std::map used for?

std::map is a sorted associative container that contains key-value pairs with unique keys. Keys are sorted by using the comparison function Compare . Search, removal, and insertion operations have logarithmic complexity. Maps are usually implemented as red-black trees.


1 Answers

Note that these two samples are only functionally equivalent if A instances are singletons. Otherwise it's very possible that two A values which are equal in value but different in address. This would lead to different semantics.

Personally I prefer the std::map<A, std::string> version because the semantics of it are crystal clear. The keys have equality semantics and there is no potentially for a dangling or nullptr value. The std::map<A*, std::string> version comes with a host of questions for the developer looking through the code

  • Who owns the key values?
  • Are all instances of A singletons? If not how do I ensure the A I'm looking for is the A* value that is stored?
  • When are the keys freed?
like image 103
JaredPar Avatar answered Sep 28 '22 21:09

JaredPar