Reputation: 30655
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....
Upvotes: 1
Views: 987
Reputation: 7132
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
Upvotes: 4
Reputation: 477580
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)
Upvotes: 1