containers


Topic: Containers

The Standard Template Library (STL) in C++ provides a collection of powerful and efficient container classes. These containers are fundamental to modern C++ programming, offering various data structures to store and manipulate collections of objects. This guide will explore the main STL containers through practical examples, demonstrating their usage and highlighting their strengths in different scenarios.

Example 1: std::vector - Dynamic Array

#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<int> numbers = {5, 2, 8, 1, 9};

    // Adding elements
    numbers.push_back(7);

    // Accessing elements
    std::cout << "First element: " << numbers[0] << std::endl;

    // Iterating
    for (const auto& num : numbers) {
        std::cout << num << " ";
    }
    std::cout << std::endl;

    // Sorting
    std::sort(numbers.begin(), numbers.end());

    // Size and capacity
    std::cout << "Size: " << numbers.size() << std::endl;
    std::cout << "Capacity: " << numbers.capacity() << std::endl;

    return 0;
}

Explanation

Example 2: std::list - Doubly Linked List

#include <iostream>
#include <list>
#include <algorithm>

int main() {
    std::list<std::string> fruits = {"apple", "banana", "cherry"};

    // Inserting elements
    fruits.push_front("kiwi");
    fruits.push_back("mango");

    // Removing elements
    fruits.pop_front();

    // Finding and erasing
    auto it = std::find(fruits.begin(), fruits.end(), "banana");
    if (it != fruits.end()) {
        fruits.erase(it);
    }

    // Iterating and printing
    for (const auto& fruit : fruits) {
        std::cout << fruit << " ";
    }
    std::cout << std::endl;

    return 0;
}

Explanation

Example 3: std::map - Associative Container

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

int main() {
    std::map<std::string, int> ages;

    // Inserting key-value pairs
    ages["Alice"] = 30;
    ages["Bob"] = 25;
    ages.insert({"Charlie", 35});

    // Accessing and modifying values
    ages["Bob"] = 26;

    // Checking if a key exists
    if (ages.count("David") == 0) {
        std::cout << "David is not in the map" << std::endl;
    }

    // Iterating through the map
    for (const auto& [name, age] : ages) {
        std::cout << name << " is " << age << " years old." << std::endl;
    }

    // Erasing an element
    ages.erase("Charlie");

    return 0;
}

Explanation

Example 4: std::unordered_set - Hash Table

#include <iostream>
#include <unordered_set>
#include <string>

int main() {
    std::unordered_set<std::string> colors = {"red", "green", "blue"};

    // Inserting elements
    colors.insert("yellow");

    // Checking for existence
    if (colors.find("purple") == colors.end()) {
        std::cout << "Purple is not in the set" << std::endl;
    }

    // Removing an element
    colors.erase("green");

    // Iterating through the set
    for (const auto& color : colors) {
        std::cout << color << " ";
    }
    std::cout << std::endl;

    // Size of the set
    std::cout << "Number of colors: " << colors.size() << std::endl;

    return 0;
}

Explanation

Summary

STL containers in C++ provide a wide range of data structures to suit different programming needs:

  1. std::vector: A dynamic array offering fast random access and efficient operations at the end.
  2. std::list: A doubly-linked list allowing constant-time insertion and removal throughout the container.
  3. std::map: An ordered associative container for key-value pairs with unique, sorted keys.
  4. std::unordered_set: A hash table implementation for fast, unordered storage of unique elements.

These examples demonstrate only a subset of the available STL containers. Other important containers include std::deque, std::set, std::multimap, std::multiset, std::unordered_map, and std::array. Each container has its own strengths and is designed for specific use cases.

When choosing a container, consider factors such as: - The type of data you need to store - The operations you'll perform most frequently (insertion, deletion, lookup, iteration) - Whether you need ordered or unordered storage - Memory usage and performance requirements

By understanding the characteristics of each container, you can select the most appropriate one for your specific programming task, leading to more efficient and maintainable code.

Related

Previous Page | Course Schedule | Course Content