C++ Maps and Their Operations

Introduction

Welcome to our data structures revision! Today, we will delve deeply into C++ Maps. Much like a bookshelf, maps allow you to quickly select the book (value) you desire by reading its label (key). They are vital to C++ for quickly accessing values using keys, as well as for efficient key insertion and deletion. So, let's explore C++ maps for a clearer understanding of these concepts.

C++ Maps

Our journey starts with C++ maps, a pivotal data structure that holds data as key-value pairs. Imagine storing your friend's contact info in such a way that allows you to search for your friend's name (the key) and instantly find their phone number (the value).

To define a map in C++, you use the std::map template from the <map> header. For example, std::map<std::string, std::string> contacts; defines a map where both keys and values are strings. This map, contacts, can store names and their corresponding phone numbers.

#include <iostream>
#include <string>
#include <map>

class PhoneBook {
public:
    PhoneBook() = default;

    void addContact(const std::string& name, const std::string& phoneNumber) {
        // Method to add a contact
        contacts[name] = phoneNumber;
    }

    std::string getPhoneNumber(const std::string& name) {
        // Method to retrieve a contact's phone number, or "None" if it's not in contacts
        if (contacts.find(name) != contacts.end()) {
            return contacts[name];
        }
        return "None";
    }

private:
    std::map<std::string, std::string> contacts;
};

// Create a PhoneBook instance
int main() {
    PhoneBook phoneBook;

    // Add contacts
    phoneBook.addContact("Alice", "123-456-7890");
    phoneBook.addContact("Bob", "234-567-8901");
    std::cout << phoneBook.getPhoneNumber("Alice") << std::endl;  // Output: 123-456-7890
    std::cout << phoneBook.getPhoneNumber("Bobby") << std::endl;  // Output: None

    return 0;
}

In the above code, we create a PhoneBook class that uses a std::map to store contacts. As you can see, maps simplify the processes of adding, modifying, and accessing information with unique keys.

Operations in Maps

C++ maps enable a variety of operations for manipulating data, such as setting, getting, and deleting key-value pairs. Understanding these operations is crucial for efficient data handling in C++.

To add or update entries in a map, you directly assign a value to a key. If the key exists, the value is updated; if not, a new key-value pair is added. This flexibility allows for dynamic updates and additions to the map without needing a predefined structure.

The find operation is used to retrieve the value associated with a specific key. It provides a safe way to access values since it allows checking if the key exists, preventing errors that would arise from attempting to access a non-existent key. If the key doesn't exist, find returns an iterator to end().

Deleting an entry is done using the erase method followed by the key. This operation removes the specified key-value pair from the map, which is essential for managing the contents of the map actively. If the key doesn't exist, erase returns 0.

Let’s see how these operations work in the context of a Task Manager class:

#include <iostream>
#include <string>
#include <map>

class TaskManager {
public:
    TaskManager() = default;

    void addOrUpdateTask(const std::string& taskName, const std::string& status) {
        // Add a new task or update an existing task
        tasks[taskName] = status;
    }

    std::string getTaskStatus(const std::string& taskName) {
        // Retrieve the status of a task; returns "Not Found" if the task does not exist
        auto it = tasks.find(taskName);
        if (it != tasks.end()) {
            return it->second;
        }
        return "Not Found";
    }

    void deleteTask(const std::string& taskName) {
        // Removes a task using its name
        if (tasks.erase(taskName) == 0) {
            std::cout << "Task '" << taskName << "' not found." << std::endl;
        }
    }

private:
    std::map<std::string, std::string> tasks;
};

// Test the TaskManager class
int main() {
    TaskManager myTasks;
    myTasks.addOrUpdateTask("Buy Milk", "Pending");
    std::cout << myTasks.getTaskStatus("Buy Milk") << std::endl;  // Output: Pending
    myTasks.addOrUpdateTask("Buy Milk", "Completed");
    std::cout << myTasks.getTaskStatus("Buy Milk") << std::endl;  // Output: Completed

    myTasks.deleteTask("Buy Milk");
    std::cout << myTasks.getTaskStatus("Buy Milk") << std::endl;  // Output: Not Found

    return 0;
}

This example showcases how to leverage map operations in C++ to effectively manage data by adding, updating, retrieving, and deleting entries through a simulated Task Manager application.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal