複合キーを含むマップを作成したいと考えています。たとえば、私は学生の名簿番号と彼/彼女が勉強している学期を持っています。ここで、roll no と semester が一緒にマップのキーとして機能するようなマップを作成したいと考えています。
4 に答える
キーの独自のクラスを定義して独自の比較演算子を定義するのではなく、ロール番号と学期のみを気にするので、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());
If you're using something other than an int for the roll number and semester, you can just as easily use those in the pair. Just keep in mind that if you're using custom structures for those objects, they'll need to implement equality and comparison operators, in which case you lose the benefit of using a pair instead of using some other structure directly.
編集:operator==()
少し疑問が生じたので、キータイプによっても提供される必要がある かどうか疑問に思いました。明らかに、で値を検索するときはmap
、内部で同等性のテストを使用する必要があるためです。しかし、2003C++標準の23.1.2/3は、それは必要ではないと述べています。2つの主要なオブジェクト間の同等性は、と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;
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)];
}
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;