Introduction
C++ provides various containers to store and manage data,
each with its unique characteristics and applicable scenarios.
This article will delve into five common sequence containers: array, vector, deque, list, and forward_list,
comparing their features, performance, and offering selection advice.
Array
std::array is a fixed-size array introduced in C++11,
combining the performance of C-style arrays with the interface of STL containers.
Characteristics
- Fixed Size: Size is determined at compile time and cannot be changed dynamically.
- Stack Allocation: Typically allocates memory on the stack, offering high performance.
- Random Access: Supports
O(1) time complexity for random access. - Iterator Support: Provides iterators, allowing use with STL algorithms.
When to Use
- When the data size is known and fixed.
- When pursuing ultimate performance, avoiding heap allocation overhead.
- When interoperability with C-style arrays is required.
Example
#include <array>
#include <iostream>
#include <numeric> // For std::accumulate
int main() {
std::array<int, 5> my_array = {1, 2, 3, 4, 5};
// Access elements
std::cout << "Element at index 2: " << my_array[2] << std::endl; // Output: 3
// Iteration
for (int& x : my_array) {
x *= 2;
}
// Sum
int sum = std::accumulate(my_array.begin(), my_array.end(), 0);
std::cout << "Sum of elements: " << sum << std::endl; // Output: 30
return 0;
}
Vector
std::vector is a dynamic array that can change its size dynamically at runtime.
It is the most commonly used and flexible sequence container in C++.