samedi 7 août 2021

How to copy a stl unordered_map from one class to another?

I have a big unordered_map, which saves a lot of data.

it looks like:

std::unordered_map<std::string, std::unordered_map<int,
  std::unordered_map<std::string, 
    std::unordered_map<std::string, double> >> > data;

As you can see, it's a multi-level map, let me explain, the data is: <store_name, <date, <goods_name, <key, value>>>>.

For example: walmat, 20200101, beer, price, 1.99 means there is a data which record, it's from walmat, the date is 20200101, goods_name is beer, price=1.99

and now, I want to save the second level map to another place, which means I want to save data.at("walmat") to my class, named A.

class A {
  // I want to avoid copy so i make A's data a pointer
  A(std::unordered_map<int, std::unordered_map<std::string, std::unordered_map<std::string, double> >>* data) : data_(data) {
  }

  std::unordered_map<int, std::unordered_map<std::string, std::unordered_map<std::string, double> >>* data_;
};

I want to avoid copy because my data is very large.

so, I think passing the pointer or reference to A, is a good idea.

but i think pass &(data.at("walmat")) is not ok for compiler,

A a(&(data.at("walmat")));

will fail to compile.

seems data.at() will return a temp variable. Can you help on this?

How can I avoid copy if I want to pass part of my map to another place?

Aucun commentaire:

Enregistrer un commentaire