Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Searching data using different keys

Tags:

c++

stl

I am no expert in C++ and STL.

I use a structure in a Map as data. Key is some class C1. I would like to access the same data but using a different key C2 too (where C1 and C2 are two unrelated classes).

Is this possible without duplicating the data? I tried searching in google, but had a tough time finding an answer that I could understand.

This is for an embedded target where boost libraries are not supported.

Can somebody offer help?

like image 668
NeonGlow Avatar asked Dec 08 '22 14:12

NeonGlow


1 Answers

You may store pointers to Data as std::map values, and you can have two maps with different keys pointing to the same data.

I think a smart pointer like std::shared_ptr is a good option in this case of shared ownership of data:

#include <map>       // for std::map
#include <memory>    // for std::shared_ptr

....

std::map<C1, std::shared_ptr<Data>> map1;
std::map<C2, std::shared_ptr<Data>> map2;

Instances of Data can be allocated using std::make_shared().

like image 198
Mr.C64 Avatar answered Dec 11 '22 03:12

Mr.C64