Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • C++
  • Standard Template Library
  • STL Vector
  • STL List
  • STL Set
  • STL Map
  • STL Stack
  • STL Queue
  • STL Priority Queue
  • STL Interview Questions
  • STL Cheatsheet
  • C++ Templates
  • C++ Functors
  • C++ Iterators
Open In App
Next Article:
What Requirements Must std::map Key Classes Meet to be Valid Keys?
Next article icon

What Requirements Must std::map Key Classes Meet to be Valid Keys?

Last Updated : 25 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In C++, std::map is a commonly used associative container that stores elements in key-value pairs, allowing for efficient data retrieval based on keys. One common question that arises is what requirements must be met for a class to be used as a key in std::map.

In this article, we will learn the requirements for key classes in std::map, understand the reasoning behind these requirements, and provide examples to illustrate their importance.

Requirements for std::map Key Classes

The std::map is part of the Standard Template Library (STL) in C++ and is implemented as a balanced binary tree. The keys in a std::map must be unique and must follow certain requirements to ensure proper functionality. To be used as a key in std::map, a class must meet the following requirements:

1. Copyable and Assignable

The key class must be copyable and assignable. This ensures that the keys can be duplicated and assigned as needed when managing the elements within the map.

2. Comparison Operator

The key class must have a valid comparison operator to define an ordering among the keys. By default, std::map uses std::less<KeyType>, which relies on the < operator. However, we can define a custom comparison operator to specify a different ordering.

If we choose not to use the default < operator, we can create a custom comparison operator. This operator must define a strict weak ordering, meaning if CmpMyType()(a, b) returns true, then CmpMyType()(b, a) must return false. Additionally, if both comparisons return false, the elements are considered equal.

Example:

The below example demonstrates the Custom Comparison Operator:

struct MyType {
int a;
std::string b;
};

struct CmpMyType {
bool operator()(const MyType& lhs, const MyType& rhs) const {
if (lhs.a < rhs.a) return true;
if (lhs.a > rhs.a) return false;
return lhs.b < rhs.b;
}
};

C++ Program to Demonstate the Valid Key Class for std::map

The below program illustrates an example of a custom class that meets the criteria for being a key in std::map to demonstrate the requirements.

C++
// C++ program to demonstrate the use of std::map with a // custom key type (Person)  #include <iostream> #include <map> #include <string>  using namespace std;  // Structure to represent a person struct Person {     int id;     string name;      // Comparison operator for strict weak ordering     bool operator<(const Person& other) const     {         if (id < other.id)             return true;         if (id > other.id)             return false;         return name < other.name;     } };  int main() {     // Declare a map with Person as key and int as value     map<Person, int> personMap;      // Inserting elements into the map     personMap[Person{ 1, "Alice" }] = 100;     personMap[Person{ 2, "Bob" }] = 200;     personMap[Person{ 3, "Charlie" }] = 300;      // Accessing and printing elements in the map     for (const auto& pair : personMap) {         cout << pair.first.name << " : " << pair.second              << endl;     }      return 0; } 

Output
Alice : 100 Bob : 200 Charlie : 300 

Note: The strict weak ordering is very important here because it allows std::map to maintain the elements in a sorted order. This ordering enables efficient operations like O(log n) lookup and insertion time by key value.

Conclusion

To be used as a key in std::map, a class must meet several requirements, including being copyable and assignable, and having a valid comparison operator to define a strict weak ordering. These requirements ensure that the keys can be ordered, managed efficiently, and integrated seamlessly with the map's underlying data structure. By understanding and meeting these requirements, we can create custom key classes that work effectively with std::map.


Next Article
What Requirements Must std::map Key Classes Meet to be Valid Keys?

B

beliver01
Improve
Article Tags :
  • C++
  • STL
  • cpp-map
Practice Tags :
  • CPP
  • STL

Similar Reads

    Map of Sets in C++ STL with Examples
    Maps are associative containers that store elements in a mapped fashion. Each element has a key value and a mapped value. No two mapped values can have same key values. Sets are a type of associative container in which each element has to be unique because the value of the element identifies it. The
    2 min read
    Why is std::map Implemented as Red-Black Tree?
    In C++, we commonly use std::map container of STL for storing key-value pairs in a sorted order. A frequent question arises: Why is std::map implemented as a Red-Black Tree instead of other data structures like hash tables or different types of trees?In this article, we will learn the reasons behind
    3 min read
    Which data structure is used by Map?
    What is a Map? Before learning the data structure used by a map, let us have an overlook of map. Map is the part of the STL library that stores key value pairs in it and no two values have the same keys but the different keys can store similar values. The map stores keys in sorted order. These are s
    2 min read
    Vector of Unordered Maps in C++ with Examples
    Vector: Vector: It is the same as dynamic arrays with the ability to resize itself automatically when an element is inserted or deleted, with their storage being handled automatically by the container. Vector elements are placed in contiguous storage so that they can be accessed and traversed using
    6 min read
    Check if a key is present in a C++ map or unordered_map
    A C++ map and unordered_map are initialized to some keys and their respective mapped values. Examples: Input : Map : 1 -> 4, 2 -> 6, 4 -> 6Check1 : 5, Check2 : 4Output : 5 : Not present, 4 : PresentC++ implementation : map // CPP code to check if a // key is present in a map #include <bi
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences