最有可能使用什么方法来处理多个键以使用 STL 容器获取值?
what is most likely used method to handle multiple keys to fetch an value using STL container?
我有三个键和一个与这些键关联的值。
所有键都是整数值。
考虑以下 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 |
+-------+--------+------------+--------+
以下哪种方法最好?
方法 1:键为字符串
string key; /* EMPID:DEPTID:COLLEGE ID */
std::map<int,string> l_container;
方法二:使用嵌套映射
int key1 ; /* =EMPID */
int key2; /* =DEPTID */
int key3; /* =COLLEGE ID */
std::map<int,std::map<int,std::map<int,string>>> l_container;
首先 - 首先创建 class 来定义您需要从此类容器中获取的内容。我相信它会是这样的:
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
};
因此,ResultsTable
的私密部分并不重要。使用这种方法,当您发现一种方法比其他方法更好时,您可以自由更改它...
那么让我们讨论一下隐私部位应该放什么:
Method1: Key as string
std::map<std::string,std::string> m_table;
那会起作用 - 但我真的不鼓励您使用它。这是不必要的复杂,在大量结果的情况下你肯定会看到性能下降...
Method2: Using nested maps
std::map<int,std::map<int,std::map<int,std::string>>> l_container;
从地图中删除键时,此方法有缺点。删除最后一个元素后,您可能会将嵌套地图留空...
方法三:使用组合键映射
std::map<std::tuple<int,int,int>, std::string> m_data;
// or
std::map<std::array<int,3>, std::string> m_data;
这个方法(评论里已经提到)应该是最好的。我个人更喜欢带有 std::array
的版本,因为键由相同类型的元素组成(此处为 int
)。
我有三个键和一个与这些键关联的值。 所有键都是整数值。
考虑以下 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 |
+-------+--------+------------+--------+
以下哪种方法最好?
方法 1:键为字符串
string key; /* EMPID:DEPTID:COLLEGE ID */
std::map<int,string> l_container;
方法二:使用嵌套映射
int key1 ; /* =EMPID */
int key2; /* =DEPTID */
int key3; /* =COLLEGE ID */
std::map<int,std::map<int,std::map<int,string>>> l_container;
首先 - 首先创建 class 来定义您需要从此类容器中获取的内容。我相信它会是这样的:
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
};
因此,ResultsTable
的私密部分并不重要。使用这种方法,当您发现一种方法比其他方法更好时,您可以自由更改它...
那么让我们讨论一下隐私部位应该放什么:
Method1: Key as string
std::map<std::string,std::string> m_table;
那会起作用 - 但我真的不鼓励您使用它。这是不必要的复杂,在大量结果的情况下你肯定会看到性能下降...
Method2: Using nested maps
std::map<int,std::map<int,std::map<int,std::string>>> l_container;
从地图中删除键时,此方法有缺点。删除最后一个元素后,您可能会将嵌套地图留空...
方法三:使用组合键映射
std::map<std::tuple<int,int,int>, std::string> m_data;
// or
std::map<std::array<int,3>, std::string> m_data;
这个方法(评论里已经提到)应该是最好的。我个人更喜欢带有 std::array
的版本,因为键由相同类型的元素组成(此处为 int
)。