Introduction

Welcome! Today, we will explore creating a simple address book application using C++ and its std::unordered_map class. This task will help you understand how to manipulate unordered maps in C++, focusing on adding, retrieving, and deleting entries. By the end of this lesson, you'll have a solid grasp of these fundamental operations.

Introducing Methods to Implement

In this task, we will implement three methods to manage our address book:

  • bool add_contact(const std::string& name, const std::string& phone_number): Adds a new contact. Returns false if the contact already exists; otherwise, adds the contact and returns true. In this task, let's assume phone numbers do not change, so it's not allowed to overwrite the existing contact's number.
  • std::string get_contact(const std::string& name): Retrieves the phone number for a given name. Returns an empty string if the contact does not exist.
  • bool delete_contact(const std::string& name): Deletes a contact with the given name. Returns true if the contact exists and is deleted, false otherwise.

Let's break down each method in detail in the next sections.

Step 1: Implementing `add_contact`

This method adds a new contact to the address book with the given name and phone_number. If the contact already exists, it returns false. Otherwise, it adds the contact and returns true.

Question: Why do you think we need to check if the contact already exists?

Answer: To avoid duplicating existing entries. If a contact with the same name already exists, we shouldn't allow overwriting its phone number in this method, as it's only for creation.

Here is the method implementation:

#include <iostream>
#include <string>
#include <unordered_map>

class AddressBook {
public:
    bool add_contact(const std::string& name, const std::string& phone_number) {
        if (contacts.find(name) != contacts.end()) {
            return false;
        }
        contacts[name] = phone_number;
        return true;
    }
    
    // To display the current contacts
    void print_contacts() const {
        for (const auto& [name, phone_number] : contacts) {
            std::cout << name << ": " << phone_number << '\n';
        }
    }

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

// Example usage:
int main() {
    AddressBook address_book;
    std::cout << std::boolalpha << address_book.add_contact("Alice", "123-456-7890") << '\n';  // true
    std::cout << address_book.add_contact("Alice", "098-765-4321") << '\n';  // false
    address_book.print_contacts();  // Alice: 123-456-7890
    return 0;
}

In this method:

  • We verify if the contact already exists using if (contacts.find(name) != contacts.end()).
  • If it exists, we return false.
  • If it doesn't exist, we add it to our unordered_map and return true.
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