VINOTH ENERGETIC
VINOTH ENERGETIC

Reputation: 1843

what is most likely used method to handle multiple keys to fetch an value using STL container?

I have three keys and one associated value with that keys. All the keys are integer value.

consider the following table

+-------+--------+------------+--------+
| EMPID | DEPTID | COLLEGE ID | RESULT |
| 1     | 1      | 1          | A      |
| 1     | 2      | 2          | B      |
| 1     | 3      | 3          | C      |
| 2     | 1      | 1          | D      |
| 2     | 2      | 2          | E      |
| 2     | 3      | 3          | F      |
+-------+--------+------------+--------+

which among the following method is best?

Method1: Key as string

string key; /* EMPID:DEPTID:COLLEGE ID */
std::map<int,string> l_container;

Method2: Using nested maps

int key1 ; /* =EMPID */
int key2; /* =DEPTID */
int key3; /* =COLLEGE ID */
std::map<int,std::map<int,std::map<int,string>>> l_container;

Upvotes: 1

Views: 40

Answers (1)

PiotrNycz
PiotrNycz

Reputation: 24402

First of all - first create class that defines what you need from such container. I believe it would be something like this:

class ResultTable
{
public:
   void addResult(int key1, int key2, int key3, std::string value);
   void removeResult(int key1, int key2, int key3);
   std::string getResult(int key1, int key2, int key3) const;
   bool isPresent(int key1, int key2, int key3) const;
private:
  ... m_table; // real container here   
};

So, it is not so much important what you have behind ResultsTable in its private part. With such approach, you are free to change it when you find one method better than other...

So lets discuss what to put in private parts:

Method1: Key as string

std::map<std::string,std::string> m_table;

That would work - but I really discourage you to use it. That is unnecessary complicated and you would for sure see performance degradation in case of big number of results...

Method2: Using nested maps

std::map<int,std::map<int,std::map<int,std::string>>> l_container;

This method has disadvantage when comes to remove keys from map. It might happen that you left nested maps empty after removing last element...

Method3: Using combined keys maps

std::map<std::tuple<int,int,int>, std::string> m_data;
// or
std::map<std::array<int,3>, std::string> m_data;

This method (already mentioned in comments) should be the best. I personally prefer the version with std::array for key consisting of elements of the same type (int here).

Upvotes: 1

Related Questions