std::vector is a dynamic container that can be used with offsets. Unlike static arrays, it can grow and shrink in size at runtime, but you can use offsets as well as iterators to navigate on them.
Some key points about std::vector
- Dynamic resizing: When you add elements to a
std::vector, it can automatically resize itself to accommodate the new elements. - Random access: You can access any element of a
std::vectorusing its index, just like a regular array. - Efficient insertion and deletion: Inserting or deleting elements at the end of a
std::vectoris very efficient. - Memory management:
std::vectorhandles memory management for you, so you don’t have to worry about allocating and deallocating memory manually. - Iterators:
std::vectorprovides iterators that allow you to iterate over its elements in a convenient way.
Example of std:vector in C++
#include <iostream>
#include <vector>
int main() {
std::vector<int> numbers;
// Add elements to the vector
numbers.push_back(1);
numbers.push_back(2);
numbers.push_back(3);
// Access elements using
their indices
std::cout << numbers[0] << std::endl;
std::cout << numbers[1] << std::endl;
std::cout << numbers[2] << std::endl;
// Iterate over the elements using a for loop
for (int number : numbers) {
std::cout << number << std::endl;
}
return 0;
}
It will output 1,2,3 and 1,2,3.
Differences between std::vector and std::list
| Feature | std::vector | std::list |
| Underlying data structure | Dynamic array | Doubly linked list |
| Random access | Yes | No |
| Insertion/deletion at the beginning/middle | Inefficient (O(n)) | Efficient (O(1)) |
| Insertion/deletion at the end | Efficient (O(1)) | Efficient (O(1)) |
| Iterators | Random access iterators | Bidirectional iterators |
| Memory usage | Generally more compact | Generally less compact (due to pointers) Export to Sheets |
std::vector is often preferred due to random access and memory efficiency, while std::list if the choice if you often need to insert at the beginning or in the middle.