Reputation: 591
From a C background I find myself falling back into C habits where there is generally a better way. In this case I can't think of a way to do this without pointers.
I would like
struct foo {
int i;
int j;
};
mymap['a'] = foo
mymap['b'] = bar
As long as only one key references a value mymap.find will return a reference so I can modify the value, but if I do this:
mymap['c'] = mymap.find('a') // problematic because foo is copied right?
The goal is to be able to find 'a' or 'c' modify foo and then the next find of 'a' or 'c' will show the updated result.
Upvotes: 3
Views: 3645
Reputation: 18864
Boost.Intrusive is a library presenting some intrusive containers to the world of C++. Intrusive containers are special containers that offer better performance and exception safety guarantees than non-intrusive containers (like STL containers).
The performance benefits of intrusive containers makes them ideal as a building block to efficiently construct complex containers like multi-index containers or to design high performance code like memory allocation algorithms.
While intrusive containers were and are widely used in C, they became more and more forgotten in C++ due to the presence of the standard containers which don't support intrusive techniques.Boost.Intrusive not only reintroduces this technique to C++, but also encapsulates the implementation in STL-like interfaces. Hence anyone familiar with standard containers can easily use Boost.Intrusive.
Upvotes: 0
Reputation: 208323
No, you will need to use pointers for this. Each entry in the map maintains a copy of the value assigned, which means that you cannot have two keys referring to the same element. Now if you store pointers to the element, then two keys will refer to two separate pointers that will refer to the exact same in memory element.
For some implementation details, std::map
is implemented as a balanced tree where in each node contains a std::pair<const Key,Value>
object (and extra information for the tree structure). When you do m[ key ]
the node containing the key is looked up or a new node is created in the tree and the reference to the Value
subobject of the pair is returned.
Upvotes: 3
Reputation: 49802
I would use std::shared_ptr
here. You have an example of shared ownership, and shared_ptr
is made for that. While pointers tend to be overused, it is nothing wrong with using them when necessary.
Upvotes: 2