CPP

C++ Standard Library Containers - Vectors, Lists, and Deques


The C++ Standard Library provides a variety of container classes to store and manipulate collections of data efficiently. Three commonly used containers are vectors, lists, and deques. In this guide, we'll explore the characteristics and usage of these containers.

Vectors

A vector is a dynamic array that can grow or shrink in size as needed. It provides efficient random access to elements. Here's how to work with vectors:

#include <iostream>
#include <vector>
using namespace std;
int main() {
    vector<int> numbers;
    // Adding elements to the vector
    numbers.push_back(10);
    numbers.push_back(20);
    numbers.push_back(30);
    // Accessing elements
    cout << `Second element: ` << numbers[1] << endl;
    // Iterating through the vector
    cout << `Vector elements: `;
    for (int num : numbers) {
        cout << num << ` `;
    }
    cout << endl;
    return 0;
}
    

Lists

A list is a doubly-linked list, which allows for efficient insertion and deletion of elements at any position. Here's how to work with lists:

#include <iostream>
#include <list>
using namespace std;
int main() {
    list<string> names;
    // Adding elements to the list
    names.push_back(`Alice`);
    names.push_back(`Bob`);
    names.push_back(`Charlie`);
    // Inserting an element
    auto it = names.begin();
    ++it; // Move to the second position
    names.insert(it, `David`);
    // Iterating through the list
    cout << `List elements: `;
    for (const string& name : names) {
        cout << name << ` `;
    }
    cout << endl;
    return 0;
}
    

Deques

A deque (double-ended queue) is a dynamic array that allows efficient insertion and deletion of elements at both ends. Here's how to work with deques:

#include <iostream>
#include <deque>
using namespace std;
int main() {
    deque<double> measurements;
    // Adding elements to the deque
    measurements.push_back(3.14);
    measurements.push_front(2.71);
    // Accessing elements
    cout << `First element: ` << measurements[0] << endl;
    // Iterating through the deque
    cout << `Deque elements: `;
    for (double value : measurements) {
        cout << value << ` `;
    }
    cout << endl;
    return 0;
}
    

Conclusion

Vectors, lists, and deques are versatile C++ Standard Library containers that offer different trade-offs in terms of efficiency and functionality. Depending on your specific use case, you can choose the container that best suits your needs. As you continue your C++ journey, you'll explore more advanced container operations and use cases.

Written by Surfside Media

Senior Full Stack Developer specializing in Web Technologies.