Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient way to map unique and duplicate value. Where key or value can be access

Tags:

c++

c++11

stdmap

There are n no of string which need to map with another string.

Ex :     Bacardi_old - > Facundo 
         Smirnoff_old -> Pyotr 
         Seagram_old  -> Joseph
         This keep on ..... may be around 1000

There are some string which need to map with duplicate string.

Ex :     Bacardi_new  -> Facundo 
         Smirnoff_new -> Facundo 
         Seagram_new  -> Facundo 

Requirement: As Below case

case 1: when brand name input. Owner name as output.

input : Bacard_old
output: Facundo

case 2: When owner name input brand name as output.

input : Facundo
output : Bacardi_old, Bacardi_new ,Smirnoff_new ,Seagram_new 

My Approach:

1.I have a map as below :

std::map<std::string,std::vector<std::string>> Mymap;

2.Should i create two map one unique mapping and another for duplicate

std::map<std::string,std::string>Mymap
std::map<std::string,std::vector<std::string>>Mymap

Is the second option good than first in terms of all the aspect. Please suggest the best approach.

Note : I am stick with c++11. No boost library.

like image 991
ava Avatar asked Oct 16 '22 12:10

ava


2 Answers

The best approach depends on your needs. Are you interested in access speed or insertion speed? Or are you interested in reducing the used memory space?

The first solution that you propose (a map with key=brand and value=owner) uses less memory but requires a full scan to perform a search by owner.

The second solution:

  • a map with key=brand and value=owner
  • a map with key=brand and value= list of owners

is faster for both search by owner and search by brand. However, it requires more memory and you also need to perform 2 insertions for each new pair.

like image 138
Amedeo Avatar answered Nov 15 '22 05:11

Amedeo


Best is highly relative :)

You can use std::multimap for the same.

std::multimap<std::string,std::string> my_map;
my_map.insert(std::make_pair("owner_name", "brand_name"));

Now you can search based on key or value depending upon what you need.

like image 30
Shravan40 Avatar answered Nov 15 '22 07:11

Shravan40