Defined in: <vector>
Overview
- Simplified
- Detailed
template< typename T, /* ... */ >
class vector;
- Regular
- Polymorphic (since C++17)
template<
class T,
class Allocator = std::allocator<T>
> class vector;
namespace pmr {
template< class T >
using vector = std::vector<T, std::pmr::polymorphic_allocator<T>>;
}
std::vector
is a container that encapsulates dynamic size arrays.
Memory
The elements are stored contiguously, one after another.
This means that a pointer to an element of a vector
may be passed to any function
that expects a pointer to an element of an array.
Storage size
The storage of the vector
is handled automatically, being expanded and contracted as needed.
Vectors usually occupy more space than static arrays, because more memory is allocated
to handle future growth. This way a vector does not need to reallocate each time an element
is inserted, but only when the additional memory is exhausted. The total amount of allocated
memory can be queried using capacity()
function.
Extra memory can be returned to the system via a call to shrink_to_fit()
(since C++11)
Reallocations are usually costly operations in terms of performance.
The reserve()
function can be used to eliminate reallocations
if the number of elements is known beforehand.
Technical details
Complexity
The complexity (efficiency) of common operations on vectors is as follows:
- random access - constant 𝓞(1)
- insertion or removal of elements at the end - amortized constant 𝓞(1)
- insertion or removal of elements - linear in the distance to the end of the vector 𝓞(n)
Named requirements
std::vector
(for T
other than bool
) meets the requirements of:
Template type requirements
T
- since C++17
- until C++17
- until C++11
Allocator
The type must meet the requirements of Allocator.- since C++20
- until C++20
Allocator::value_type
is not the same as T
.Allocator::value_type
is not the same as T
.std::vector
Defined in | vector |
Template parameters
See technical details for more detailed information.
pub | T | Type of the elements. |
pub | Allocator | Allocator that is used to acquire/release memory and to construct/destroy the elements in that memory. |
Type names
pub | value_type | T |
pub | allocator_type | Allocator |
pub | size_type | Unsigned integer type (usually std::size_t ) |
pub | difference_type | Signed integer type (usually std::ptrdiff_t ) |
pub | reference | value_type& |
pub | const_reference | value_type const& |
pub | pointer | Allocator::pointer (until C++11)std::allocator_traits<Allocator>::pointer (since C++11) |
pub | const_pointer | Allocator::const_pointer (until C++11)std::allocator_traits<Allocator>::const_pointer (since C++11) |
pub | iterator |
|
pub | const_iterator |
|
pub | reverse_iterator | std::reverse_iterator<iterator> |
pub | const_reverse_iterator | std::reverse_iterator<const_iterator> |
Member functions
pub | (constructors) | Constructs a vector. |
pub | (destructor) | Destroys the vector, deallocating internal storage if used. |
pub | operator= | Assigns values to the container. |
pub | assign | Assigns values to the container. |
pub | get_allocator | Returns the associated allocator. |
Element access
pub | at | Accesses a specified element with bounds checking. |
pub | operator[] | Accesses a specified element. |
pub | front | Returns the first element. |
pub | back | Returns the last element. |
pub | data | Returns a pointer to the first element of the underlying array. |
Iterators
pub | begin cbegin (since C++11) | Returns an |
pub | end cend (since C++11) | Returns an |
pub | rbegin crbegin (since C++11) | Returns a reverse |
pub | rend crend (since C++11) | Returns a reverse |
Capacity
pub | empty | Returns |
pub | size | Returns the number of elements. |
pub | max_size | Returns the maximum possible number of elements. |
pub | reserve | Reserves storage. |
pub | capacity | Returns the number of elements that can be held in currently allocated storage. |
pub | shrink_to_fit (since C++11) | Reduces memory usage by freeing unused memory. |
Operations
pub | clear | Clears the contents. |
pub | insert | Inserts elements. |
pub | emplace (since C++11) | Constructs elements in-place. |
pub | erase | Removes elements. |
pub | push_back | Appends an element to the end. |
pub | emplace_back (since C++11) | Constructs elements in-place at the end. |
pub | pop_back | Removes the last element. |
pub | resize | Changes the number of elements stored. |
pub | swap | Swaps the contents. |
Non-member functions
pub | operator== operator!= (removed in C++20) operator< (removed in C++20) operator> (removed in C++20) operator<= (removed in C++20) operator>= (removed in C++20) operator<=> | Lexicographically compares the values in the vector. |
pub | std::swap (std::vector) | An overload for a std::swap algorithm. |
pub | erase (std::vector) erase_if (std::vector) | Overloads for std::erase/std::erase_if algorithms. |
Deduction guides (since C++17)
Click to expand
Deduction guides
// (1)
template< class InputIt,
class Alloc = std::allocator<typename std::iterator_traits<InputIt>::value_type> >
vector( InputIt, InputIt, Alloc = Alloc() )
-> vector<typename std::iterator_traits<InputIt>::value_type, Alloc>;
(1)
allows deduction from an iterator range.
Overload resolution
In order for any of the deduction guides to participate in overload resolution, the folllowing requirements must be met:
InputIt
satisfies the requirements ofLegacyInputIterator
Alloc
satisfies the requirements ofAllocator
The extent to which the library determines that a type does not satisfy LegacyInputIterator
is unspecified,
except that as a minimum:
- Integral types do not qualify as input iterators.
Likewise, the extent to which it determines that a type does not satisfy Allocator
is unspecified,
except that as a minimum:
- The member type
Alloc::value_type
must exist. - The expression
std::declval<Alloc&>().allocate(std::size_t{})
must be well-formed when treated as an unevaluated operand.
Examples
Basic usage
Calculate arithmetic mean
#include <iostream>
#include <vector>
auto main() -> int
{
auto const numbers = std::vector<double>{
5, 2.4, 3.2, 1.8, 4.6,
3.1, 2.9, 4.7, 3.8, 2.2,
};
auto sum = 0.0;
for (auto number : numbers) {
sum += number;
}
auto const mean = sum / numbers.size();
std::cout << "Mean: " << mean << '\n';
}
Mean: 3.37
Find the maximum element
#include <iostream>
#include <string>
#include <algorithm>
auto main() -> int
{
auto const numbers = std::vector<int>{
5, 2, 8, 1, 14, 3, 2, 10, 3, 2
};
auto const max_it = std::max_element(
numbers.begin(),
numbers.end()
);
auto const max_index = std::distance(numbers.begin(), max_it);
std::cout << "Max: " << *max_it << " at index: " << max_index;
}
Max: 14 at index: 4
Erase nth element
#include <iostream>
#include <vector>
#include <string>
auto main() -> int
{
auto player_names = std::vector<std::string>{
"Sad Crab", "Happy Wolf", "Angry Panda",
"Wicked Witch", "Crazy Clown", "Funny Monkey",
};
auto const n = 2; // arbitrary, 0-based index
// Erase the nth element ("Angry Panda")
player_names.erase(player_names.begin() + n);
for (auto const& name : player_names) {
std::cout << name << '\n';
}
}
Sad Crab
Happy Wolf
Wicked Witch
Crazy Clown
Funny Monkey
Hover to see the original license.