我有三个键和一个与这些键关联的值。 所有键都是整数值。
考虑下表
+-------+--------+------------+--------+
| 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 |
+-------+--------+------------+--------+
以下哪种方法最好?
方法一:键为字符串
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 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
的私有(private)部分背后的内容并不那么重要。使用这种方法,当您发现一种方法比其他方法更好时,您可以自由更改它...
那么让我们讨论一下隐私部分应该放些什么:
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;
从 map 中删除键时,此方法有缺点。删除最后一个元素后,您可能会将嵌套映射留空...
方法三:使用组合键映射
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
)。
关于c++ - 最有可能使用什么方法来处理多个键以使用 STL 容器获取值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37165826/