簡體   English   中英

從復合鍵創建C ++映射

[英]Creating C++ map from composite key

我想創建一個包含復合鍵的地圖。 例如,我有學生名冊和他/她正在學習的學期。 現在,我想創建一個地圖,以使否和學期一起充當該地圖的鍵。

我只需要使用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,則可以輕松地使用它們。 請記住,如果您為這些對象使用自定義結構,則它們將需要實現相等和比較運算符,在這種情況下,您將失去使用一對而不是直接使用其他結構的好處。

編輯:一時的疑惑使我想知道是否還必須由鍵類型提供operator==() ,因為顯然當在map查找值時,必須在幕后使用相等性測試。 但是2003 C ++標准中的23.1.2 / 3表示沒有必要:兩個關鍵對象ab之間的相等性需要通過檢查a < bb < 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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM