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);
};
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.
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.
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.
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
A
singletons? If not how do I ensure the A
I'm looking for is the A*
value that is stored? If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With