C++ Map
The C++ map is an associative container that stores elements in key-value pairs, where each key is unique within the map and maps to a corresponding value.
For Example:A map of student where Student ID is the key and name is the value can be represented as:
Here is an example of how to create a map of student
// Create a map to store <student ID, name>
std::map<int, std::string> student;
Insert the student’s name into the student Map
// Insert some sample data
student[6] = "John";
student[7] = "Sarah";
student[8] = "Mark";
Iterating over a map and printing its contents
// Iterate and print the map
std::cout << "Students:" << std::endl;
for(auto it = student.begin(); it != student.end(); ++it)
{
std::cout << it->first << " => " << it->second << std::endl;
}
The auto keyword in C++ is used to automatically deduce the type of a variable from its initializer. Here are some examples of using auto:
// The type of 'i' is deduced to be int
auto i = 5;
// The type of 'd' is deduced to be double
auto d = 3.14;
// The type of 's' is deduced to be std::string
auto s = "Hello";
Here are a few different ways to delete a key-value pair from a C++ map:
- Use map.erase()
std::map<int, std::string> student;
student.erase(3); // erases element with key 3
2. Use the iterator returned by find()
std::map<int, std::string> student;
auto it = student.find(5);
if (it != student.end())
{
student.erase(it);
}
3. Assign NULL to the key
std::map<int, std::string> student;
student[2] = NULL; // erases key 2
4. Reassign the key
std::map<int, std::string> student;
student[4] = "New Value"; // erases previous value for key 4
5. Clear the entire map
std::map<int, std::string> student;
student.clear(); // removes all elements
So in summary, to delete a single key, use student.erase(), find() + erase(), assign NULL or reassign the key.To delete all keys, call student.clear().
continue….