C++ Standard Library - Maps and Sets


Maps and sets are fundamental data structures in C++ Standard Library for efficiently storing and retrieving key-value pairs and unique elements, respectively. In this guide, we'll explore the concepts of maps and sets in C++ and provide sample code to illustrate their usage.


std::map

A `std::map` is an associative container that stores key-value pairs. The keys are unique and sorted in ascending order. Here's an example of using a `std::map` to store and access key-value pairs:


#include <iostream>
#include <map>
using namespace std;
int main() {
map<string, int> ages;
ages["Alice"] = 25;
ages["Bob"] = 30;
ages["Charlie"] = 22;
cout << "Alice's age: " << ages["Alice"] << endl;
return 0;
}

In this example, we create a `std::map` named `ages` to store ages associated with names. We add key-value pairs and retrieve Alice's age using the subscript operator `[]`.


std::set

A `std::set` is a container that stores unique elements in a sorted order. Here's an example of using a `std::set` to store and access unique elements:


#include <iostream>
#include <set>
using namespace std;
int main() {
set<int> uniqueNumbers;
uniqueNumbers.insert(5);
uniqueNumbers.insert(2);
uniqueNumbers.insert(8);
uniqueNumbers.insert(2); // Duplicate, not added
cout << "Number of unique elements: " << uniqueNumbers.size() << endl;
return 0;
}

In this example, we create a `std::set` named `uniqueNumbers` to store unique integer values. We insert elements, including a duplicate, and check the number of unique elements in the set.


Iterating Over Maps and Sets

You can iterate over the elements in a `std::map` or `std::set` using iterators. Here's an example:


#include <iostream>
#include <map>
#include <set>
using namespace std;
int main() {
map<string, int> ages;
set<string> names;
ages["Alice"] = 25;
ages["Bob"] = 30;
ages["Charlie"] = 22;
names.insert("Alice");
names.insert("Bob");
names.insert("Charlie");
// Iterate over the map
for (const auto& entry : ages) {
cout << entry.first << " is " << entry.second << " years old." << endl;
}
// Iterate over the set
for (const string& name : names) {
cout << name << endl;
}
return 0;
}

In this example, we iterate over the elements in the `std::map` and `std::set` and print their contents.


Conclusion

C++ Standard Library provides powerful containers for efficiently storing and managing data. `std::map` is ideal for key-value pairs, and `std::set` ensures unique and sorted elements. Understanding and using these containers can simplify your C++ code and enhance data management in your programs.