STL std::map 的 Key 型別可以是類別型別,但該類別**必須實作 operator<**(或提供自訂比較函式物件),以便 map 內部紅黑樹進行排序與查找。
struct MyKey {
int id;
std::string name;
// 必須定義嚴格弱序
bool operator<(const MyKey& other) const {
if (id != other.id) return id < other.id;
return name < other.name;
}
};
// 使用
std::map<MyKey, std::string> myMap;
myMap[{1, "Alice"}] = "Data1";
myMap[{2, "Bob"}] = "Data2";
若不想修改類別定義(如第三方庫),可傳入比較函式物件:
struct KeyComparator {
bool operator()(const MyKey& a, const MyKey& b) const {
return a.id < b.id; // 僅比較 id
}
};
std::map<MyKey, std::string, KeyComparator> myMap;
a<b && b<a 同時為真,或 !(a<b) && !(b<a) && a!=b。std::strong_ordering 簡化三向比較。自訂類別作 Key 時,operator< 應盡量輕量,避免昂貴運算(如字串大量比對),必要時可預先計算 hash 值或使用 std::unordered_map 搭配自訂 Hash 函式。
掌握 Key 型別需求與比較器設計,即能靈活運用 std::map 處理複雜鍵值對應場景。