'How to reference a vector value to a map c++

I want to have a value stored in my vector, that same value that references the value of the key in the map and both have the same value.

std::vector<int> values;

std::map<std::string, int*> reference_value;


Solution 1:[1]

Assuming you are going to perform any operation on the vector that may invalidate the vector's iterators (insert, push_back, resize, etc.), the example you posted won't work.

std::vector works by allocating a contiguous chunk of memory to store all your values. It may allocate space for a few extra values to avoid re-allocating on each insertion, but ultimately it will need to allocate a bigger chunk of memory to fit newly inserted values. Thus, it will move all the existing values into the newly allocated chunk of memory, and free()/delete the old one. This means, that addresses of all the values in the vector will change. After this, all pointers in your unordered_map would become invalid.

To workaround this, you may use a std::shared_ptr to hold a pointer to the underlying value. If the vector is reallocated, the std::shared_ptrs will be moved, but the addresses they hold will be unaffected.

std::vector<std::shared_ptr<int>> values;
std::unordered_map<std::string, std::shared_ptr<int>> reference_value;

However, beware of the overhead of using a shared pointer.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Daniel Vrátil