11

我想创建一个包含复合键的地图。例如,我有学生的姓名和他/她正在学习的学期。现在我想创建一个地图,让卷号和学期一起作为地图的关键。

4

4 回答 4

13

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

于 2012-10-18T06:20:29.517 回答
8

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

#include <map>

struct key {
    int rollNo;
    int semester;
    string whateverElse;

    // Provide a "<" operator that orders keys.
    // The way it orders them doesn't matter, all that matters is that
    // it orders them consistently.
    bool operator<(key const& other) const {
        if (rollNo < other.rollNo) return true; else
        if (rollNo == other.rollNo) {
            if (semester < other.semester) return true; else
            if (semester == other.semester) {
                if (whateverElse < other.whateverElse) return true;
            }
        }

        return false;
    }
};

std::map<key, whateverValueTypeYouWant> dictionary;
于 2012-10-18T06:13:41.207 回答
1

std::map 键需要实现 operator< 用于键搜索和插入。例子:

#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)];
}
于 2012-10-18T06:17:59.300 回答
1

您可以定义一个包含 roll_no 和学期成员的结构类型。

        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;
于 2012-10-18T06:19:55.837 回答