c++ - 最有可能使用什么方法来处理多个键以使用 STL 容器获取值?

标签 c++ data-structures stl std

我有三个键和一个与这些键关联的值。 所有键都是整数值。

考虑下表

+-------+--------+------------+--------+
| 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/

相关文章:

c++ - 在 Visual Studio Proj 中使用 QT .qrc 文件...?

c++ - 如何将pdf文件存储为二进制文件

c++ - 使用本地 ipv6 套接字将 UDP 发送到本地 ipv4 地址

c++ - 在双链表数据结构类实验室项目中实现append和insertAt函数

c++ - 二维字符数组的全局和局部声明

python - 具有 O(1) 随机移除和添加的数据结构,用于混洗生成器顺序

c++ - 一个函数可以同时接受迭代器和反向迭代器作为参数吗

C++:列表迭代器与 vector 迭代器

c++ - 如何访问链接列表的私有(private) vector

c++ - 将 vector <char> 复制到二维 vector <string> c++