从组合键创建C ++映射

时间:2012-10-18 06:09:46

标签: c++ map

我想创建一个包含复合键的地图。例如,我有学生没有和他/她正在学习的学期。现在我想创建一个地图,使得roll no和semester一起充当地图的关键。

4 个答案:

答案 0 :(得分:10)

不是为键定义自己的类,而是必须定义自己的比较运算符,因为你只关心滚动号和学期,我使用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以外的东西,你可以很容易地使用它们中的那些。请记住,如果您为这些对象使用自定义结构,他们需要实现相等和比较运算符,在这种情况下,您将失去使用一对而不是直接使用其他结构的好处。

答案 1 :(得分:8)

编辑:片刻的疑问让我想知道operator==()是否也必须由密钥类型提供,因为很明显在查找{{1}中的值时必须在引擎盖下使用相等的测试。但是2003 C ++标准中的23.1.2 / 3表示没有必要:两个关键对象mapa之间的相等性需要通过检查两个b来确定。而a < b是假的。 :)

b < a

答案 2 :(得分:1)

std :: map键需要实现运算符&lt;用于密钥搜索和插入。 示例:

#include <map>
struct Student
{
  Student(int roll_no, int semestre)
  : roll_no(roll_no), semestre(semestre)
  {}
  int roll_no;
  int semestre;
  bool operator< (Student const &s) const
  {
    return semestre* 100000+ roll_no< s.semestre* 100000+ s.roll_no;
  }
};

#include <iostream>
#include <ostream>

int main()
{
  std::map<Student, int> m;
  m[Student(1, 1)]= 42;
  m[Student(1, 2)]= 43;
  std::cout<< m[Student(1, 1)];
}

答案 3 :(得分:1)

您可以定义包含roll_no和semester成员的结构类型。

        struct stu_key
        {   
            int roll_no;
            int semester;

            bool operator <(const stu_key &sk) const
            {   
               //compare roll_no and semester 
            }   
        };

        std::map<stu_key , value_type> stu_map;