1

If I have a std::map and std::unordered_map how could I use pointers on the double so that when the unordered_map updates the double value for a particular key, this is already reflected in the std::map for the same "key"?

So:

unordered_map["1"] = 6 causes map["1"] to be 6 also....

user997112
  • 29,025
  • 43
  • 182
  • 361

2 Answers2

4

There's no reason why you can't use pointers.

Example:

#include <iostream>
#include <map>
#include <unordered_map>
#include <memory>

int main()
{
    std::unordered_map<std::string, std::shared_ptr<double>> umap;
    std::map<std::string, std::shared_ptr<double>> omap;

    std::shared_ptr<double> value(new double(1234.5));

    umap.emplace("key", value);
    omap.emplace("key", value);

    std::cout << "umap " << *umap["key"] << "\n";
    std::cout << "omap " << *omap["key"] << "\n";

    *umap["key"] = 9999.1;
    std::cout << "omap " << *omap["key"] << "\n";
}

Output:

umap 1234.5
omap 1234.5
omap 9999.1
goji
  • 6,911
  • 3
  • 42
  • 59
1

Maybe like this:

std::unordered_map<std::string, double> um;
std::unordered_map<std::string, double*> om;

om["1"] = &um["1"];

From now on, *om["1"] is always the value of the corresponding element in um. Just make sure you never delete elements from the unordered map.

(Source: iterator and reference invalidation rules)

Community
  • 1
  • 1
Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
  • Even rehashing will invalidate iterators and references won't it? Not just erasure. – goji Oct 03 '13 at 23:17
  • 1
    @Troy: rehashing invalidates iterators but not references. (Because it doesn't move the data around, but it changes the iteration order.) – rici Oct 03 '13 at 23:30
  • 1
    @Troy: 23.2.5p9 "Rehashing invalidates iterators, changes ordering between elements, and changes which buckets elements appear in, but does not invalidate pointers or references to elements." – rici Oct 03 '13 at 23:33