Can I have a C ++ map where multiple keys refer to a value without using pointers?

Against the background of C, I find myself falling into C habits, where is usually the best way. In this case, I cannot think of a way to do it without pointers.

I would like to

struct foo {
    int i;
    int j;
};

mymap['a'] = foo
mymap['b'] = bar

      

So far, only one key is referencing the value mymap.find returns a link so I can change the value, but if I do:

mymap['c'] = mymap.find('a') // problematic because foo is copied right?

      

The goal is to find "a" or "c" to change foo, and then the next find "a" or "c" will show the updated result.

+3


source to share


3 answers


No, you will need to use pointers for this. Each map entry maintains a copy of the assigned value, which means that you cannot have two keys referencing the same item. Now, if you are storing pointers to an element, then the two keys will refer to two separate pointers, which will refer to the same thing in the memory element.



For some implementation details, it std::map

is implemented as a balanced tree, where each node contains an object std::pair<const Key,Value>

(and additional information for the tree structure). When you do m[ key ]

, a search for the node containing the key or a new node is created in the tree and a reference to the Value

pair's subobject is returned .

+2


source


I would use std::shared_ptr

here. You have a sharing example, and that's what it is for shared_ptr

. While pointers are generally overused, there is nothing wrong with using them when needed.



+2


source


Boost.Intrusive

Boost.Intrusive is a library representing some intrusive containers to the C ++ world. Intrusive containers are special containers that provide better performance and exception safety guarantees than non-intrusive containers (like STL containers).

The advantages of using intrusive containers make them ideal as a building block for efficiently creating complex containers such as multi-index containers or for developing high-performance code such as memory allocation algorithms.

While intrusive containers have been and are widely used in C, they have become more and more forgotten in C ++ due to the presence of standard containers that do not support intrusive methods. not only reintroduces this technique in C ++, but also encapsulates the implementation in STL-like interfaces. Hence, anyone familiar with standard containers can easily use Boost.Intrusive.

0


source







All Articles