我想创建一个包含复合键的 map 。例如,我有学生的卷号和他/她正在学习的学期。现在我想创建一个 map ,以便将 roll no 和 semester 一起作为 map 的键。
最佳答案
与其为键定义您自己的类并且必须定义您自己的比较运算符,因为您只关心卷号和学期,我会使用 std::pair。
#include <utility>
#include <map>
// This maps an std::pair of (roll number, semester) to a StudentRecord.
std::map<std::pair<int, int>, StudentRecord> studentMap;
studentMap.insert(std::pair<std::pair<int, int>, StudentRecord>(std::make_pair(100, 100), StudentRecord());
如果您使用的不是 int 类型的卷号和学期,您可以轻松地使用这对中的那些。请记住,如果您为这些对象使用自定义结构,它们将需要实现相等和比较运算符,在这种情况下,您将失去使用一对而不是直接使用其他结构的好处。
关于c++ - 从复合键创建 C++ 映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12948140/