Skip to main content

Lesson 6 of 7

Mini Project Part 8 - STL Contact Book

Build a complete contact book using multiple STL containers: `vector` for contact storage, `unordered_map` for O(1) ID lookup, `map<string,vector<int>>` for tag indexing, `string_view` in all search functions, and STL algorithms for sorting, filtering, and aggregation. A complete real-world use of the STL module.

16 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Contact Book - Multiple Containers & STL Algorithms

Contact Book - Multiple Containers & STL Algorithms
#include <iostream>
#include <vector>
#include <unordered_map>
#include <map>
#include <algorithm>
#include <numeric>
#include <string>
#include <string_view>
#include <iomanip>
#include <stdexcept>

struct Contact {
    int         id;
    std::string name;
    std::string phone;
    std::string email;
    std::vector<std::string> tags;
};

class ContactBook {
    std::vector<Contact>                    contacts_;         // main storage
    std::unordered_map<int, size_t>         id_to_idx_;       // O(1) lookup
    std::map<std::string, std::vector<int>> tag_index_;       // sorted tag map
    int                                     next_id_ = 1;

public:
    int add(std::string name, std::string phone,
            std::string email, std::vector<std::string> tags = {}) {
        int id = next_id_++;
        Contact c{id, std::move(name), std::move(phone),
                  std::move(email), std::move(tags)};

        id_to_idx_[id] = contacts_.size();
        for (const auto& tag : c.tags) tag_index_[tag].push_back(id);
        contacts_.push_back(std::move(c));
        return id;
    }

    const Contact& find_by_id(int id) const {
        auto it = id_to_idx_.find(id);
        if (it == id_to_idx_.end()) throw std::out_of_range("Contact not found");
        return contacts_.at(it->second);
    }

    // string_view - no copy for search
    std::vector<const Contact*> search_by_name(std::string_view query) const {
        std::vector<const Contact*> results;
        std::copy_if(contacts_.begin(), contacts_.end(),
                     std::back_inserter(results),
                     [query](const Contact& c) {
                         return std::string_view(c.name).find(query)
                                != std::string_view::npos;
                     });
        return results;
    }

    std::vector<const Contact*> find_by_tag(std::string_view tag) const {
        std::vector<const Contact*> results;
        auto it = tag_index_.find(std::string(tag));
        if (it == tag_index_.end()) return results;
        for (int id : it->second) results.push_back(&find_by_id(id));
        return results;
    }

    // Sort by name - returns copies sorted
    std::vector<Contact> sorted_by_name() const {
        auto copy = contacts_;
        std::sort(copy.begin(), copy.end(),
                  [](const Contact& a, const Contact& b){ return a.name < b.name; });
        return copy;
    }

    size_t size() const { return contacts_.size(); }

    void print_all() const {
        auto sorted = sorted_by_name();
        std::cout << std::left;
        std::cout << std::setw(4)  << "ID"
                  << std::setw(20) << "Name"
                  << std::setw(16) << "Phone"
                  << "Tags
";
        std::cout << std::string(60, '-') << "
";
        for (const auto& c : sorted) {
            std::cout << std::setw(4) << c.id
                      << std::setw(20) << c.name
                      << std::setw(16) << c.phone;
            for (size_t i = 0; i < c.tags.size(); ++i) {
                if (i) std::cout << ",";
                std::cout << c.tags[i];
            }
            std::cout << "
";
        }
    }
};

int main() {
    ContactBook book;

    book.add("Alice Smith",  "+1-555-0101", "alice@e.com",  {"friend", "work"});
    book.add("Bob Jones",    "+1-555-0102", "bob@e.com",    {"work"});
    book.add("Charlie Brown","+1-555-0103", "charlie@e.com",{"friend"});
    book.add("Alice Wu",     "+1-555-0104", "awu@e.com",    {"work", "vip"});
    book.add("David Kim",    "+1-555-0105", "dk@e.com",     {"vip"});

    book.print_all();

    std::cout << "
=== Search 'Alice' ===
";
    for (const auto* c : book.search_by_name("Alice")) {
        std::cout << "  " << c->id << ": " << c->name << "
";
    }

    std::cout << "
=== Tag 'work' ===
";
    for (const auto* c : book.find_by_tag("work")) {
        std::cout << "  " << c->name << "
";
    }

    std::cout << "
=== find by id=3 ===
";
    std::cout << book.find_by_id(3).name << "
";

    return 0;
}

Common Mistakes

  • Storing index into `contacts_` in `id_to_idx_` breaks when contacts are erased - index-based lookup requires the vector to never reorder or erase elements. For a production contact book with deletion, store `Contact::id` and linear-search, or use `map<int, Contact>` instead.
  • Tag index not updated on contact deletion - if a contact is removed, all its tags must also be removed from `tag_index_`. Forgetting this creates dangling IDs in the tag index. Implement a proper `remove` that cleans both structures.
  • Not sorting before binary search - `std::binary_search` on `contacts_` would require O(n log n) sort first. For linear-search by name, `find_if` is correct O(n). For O(log n) persistent sorted lookup, add a `map<string,int>` name-to-id index.

Tip

Tip

Practice Mini Project Part 8 STL Contact Book in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Integrating std::map, std::vector, STL Algorithms (sort, find_if) & Lambda Filters

Practice Task

Note

Practice Task - (1) Write a working example of Mini Project Part 8 STL Contact Book from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with Mini Project Part 8 STL Contact Book is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready cpp code.

Key Takeaways

  • Build a complete contact book using multiple STL containers: `vector` for contact storage, `unordered_map` for O(1) ID lookup, `map<string,vector<int>>` for tag indexing, `string_view` in all search functions, and STL algorithms for sorting, filtering, and aggregation.
  • Storing index into `contacts_` in `id_to_idx_` breaks when contacts are erased - index-based lookup requires the vector to never reorder or erase elements. For a production contact book with deletion, store `Contact::id` and linear-search, or use `map<int, Contact>` instead.
  • Tag index not updated on contact deletion - if a contact is removed, all its tags must also be removed from `tag_index_`. Forgetting this creates dangling IDs in the tag index. Implement a proper `remove` that cleans both structures.
  • Not sorting before binary search - `std::binary_search` on `contacts_` would require O(n log n) sort first. For linear-search by name, `find_if` is correct O(n). For O(log n) persistent sorted lookup, add a `map<string,int>` name-to-id index.

Topics in This Module

0/7 done