Namespaces
Variants
Views
Actions

Difference between revisions of "cpp/container/vector"

From cppreference.com
< cpp‎ | container
m (r2.7.3) (Robot: Adding de:cpp/container/vector)
m (See also: +)
 
(185 intermediate revisions by 69 users not shown)
Line 1: Line 1:
 
{{cpp/title|vector}}
 
{{cpp/title|vector}}
 
{{cpp/container/vector/navbar}}
 
{{cpp/container/vector/navbar}}
{{ddcl | header=vector |
+
{{dcl begin}}
 +
{{dcl header|vector}}
 +
{{dcl|num=1|1=
 
template<
 
template<
 
     class T,
 
     class T,
     class Allocator {{=}} std::allocator<T>
+
     class Allocator = std::allocator<T>
 
> class vector;
 
> class vector;
}}  
+
}}
 +
{{dcl|since=c++17|num=2|1=
 +
namespace pmr {
 +
    template< class T >
 +
    using vector = std::vector<T, std::pmr::polymorphic_allocator<T>>;
 +
}
 +
}}
 +
{{dcl end}}
  
{{tt|std::vector}} is a sequence container that encapsulates dynamic size arrays.
+
@1@ {{tt|std::vector}} is a sequence container that encapsulates dynamic size arrays.
 +
@2@ {{tt|std::pmr::vector}} is an alias template that uses a [[cpp/memory/polymorphic_allocator|polymorphic allocator]].
  
The elements are stored contiguously, which means that elements can be accessed not only through iterators, but also using offsets on regular pointers to elements. 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.
+
The elements are stored contiguously, which means that elements can be accessed not only through iterators, but also using offsets to regular pointers to elements. 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.
  
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 {{rlf|capacity}} function. Extra memory can be returned to the system via a call to {{rlf|shrink_to_fit}}.
+
The storage of the vector is handled automatically, being expanded 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 {{lc|capacity()}} function. Extra memory can be returned to the system via a call to {{lc|shrink_to_fit()}}<ref>In libstdc++, {{tt|shrink_to_fit()}} is [https://gcc.gnu.org/onlinedocs/libstdc++/manual/strings.html#strings.string.shrink not available] in C++98 mode.</ref>.
  
Reallocations are usually costly operations in terms of performance. {{rlf|reserve}} function can be used to eliminate reallocations if the number of elements is known beforehand.
+
Reallocations are usually costly operations in terms of performance. The {{lc|reserve()}} function can be used to eliminate reallocations if the number of elements is known beforehand.
  
 
The complexity (efficiency) of common operations on vectors is as follows:
 
The complexity (efficiency) of common operations on vectors is as follows:
  
* Random access - constant {{math|O(1)}}
+
* Random access - constant {{math|𝓞(1)}}.
* Insertion or removal of elements at the end - amortized constant {{math|O(1)}}
+
* Insertion or removal of elements at the end - amortized constant {{math|𝓞(1)}}.
* Insertion or removal of elements - linear in distance to the end of the vector {{math|O(n)}}
+
* Insertion or removal of elements - linear in the distance to the end of the vector {{math|𝓞(n)}}.
  
{{tt|std::vector}} meets the requirements of {{concept|Container}}, {{concept|AllocatorAwareContainer}}, {{concept|SequenceContainer}} and {{concept|ReversibleContainer}}.
+
{{tt|std::vector}} (for {{tt|T}} other than {{c/core|bool}}) meets the requirements of {{named req|Container}}{{rev inl|since=c++11|, {{named req|AllocatorAwareContainer}}}}, {{named req|SequenceContainer}}{{rev inl|since=c++17|, {{named req|ContiguousContainer}}}} and {{named req|ReversibleContainer}}.
 +
 
 +
{{rrev|since=c++20|
 +
Member functions of {{tt|std::vector}} are {{c/core|constexpr}}: it is possible to create and use {{tt|std::vector}} objects in the evaluation of a constant expression.
 +
 
 +
However, {{tt|std::vector}} objects generally cannot be {{c/core|constexpr}}, because any dynamically allocated storage must be released in the same evaluation of constant expression.
 +
}}
 +
 
 +
<references/>
 +
 
 +
===Template parameters===
 +
{{par begin}}
 +
{{par inc|cpp/container/param list T|vector}}
 +
{{par inc|cpp/container/param list Allocator|vector}}
 +
{{par end}}
  
 
===Specializations===
 
===Specializations===
The standard library provides a specialization of {{tt|std::vector}} for the type {{c|bool}}, which is optimized for space efficiency.
+
The standard library provides a specialization of {{tt|std::vector}} for the type {{c/core|bool}}, which may be optimized for space efficiency.
{{dcl list begin}}
+
{{dsc begin}}
{{dcl list template | cpp/container/dcl list vector_bool}}
+
{{dsc inc|cpp/container/dsc vector bool}}
{{dcl list end}}
+
{{dsc end}}
 +
 
 +
===Iterator invalidation===
 +
{|class="dsctable" style="font-size:0.9em"
 +
!Operations
 +
!Invalidated
 +
|-
 +
|All read only operations
 +
|Never.
 +
|-
 +
|{{lc|swap}}, {{lc|std::swap}}
 +
|{{lc|end()}}
 +
|-
 +
|{{lc|clear}}, {{lc|1=operator=}}, {{lc|assign}}
 +
|Always.
 +
|-
 +
|{{lc|reserve}}, {{lc|shrink_to_fit}}
 +
|If the vector changed capacity, all of them. If not, none.
 +
|-
 +
|{{lc|erase}}
 +
|Erased elements and all elements after them (including {{lc|end()}}).
 +
|-
 +
|{{lc|push_back}}, {{lc|emplace_back}}
 +
|If the vector changed capacity, all of them. If not, only {{lc|end()}}.
 +
|-
 +
|{{lc|insert}}, {{lc|emplace}}
 +
|If the vector changed capacity, all of them.<br>If not, only those at or after the insertion point (including {{lc|end()}}).
 +
|-
 +
|{{lc|resize}}
 +
|If the vector changed capacity, all of them. If not, only {{lc|end()}} and any elements erased.
 +
|-
 +
|{{lc|pop_back}}
 +
|The element erased and {{lc|end()}}.
 +
|}
  
 
===Member types===
 
===Member types===
{{dcl list begin}}
+
{{dsc begin}}
{{dcl list hitem | Member type | Definition}}
+
{{dsc hitem|Member type|Definition}}
{{dcl list template | cpp/container/dcl list value_type | vector}}
+
{{dsc inc|cpp/container/dsc value_type|vector}}
{{dcl list template | cpp/container/dcl list allocator_type | vector}}
+
{{dsc inc|cpp/container/dsc allocator_type|vector}}
{{dcl list template | cpp/container/dcl list size_type | vector}}
+
{{dsc inc|cpp/container/dsc size_type|vector}}
{{dcl list template | cpp/container/dcl list difference_type | vector}}
+
{{dsc inc|cpp/container/dsc difference_type|vector}}
{{dcl list template | cpp/container/dcl list reference | vector}}
+
{{dsc inc|cpp/container/dsc reference|vector}}
{{dcl list template | cpp/container/dcl list const_reference | vector}}
+
{{dsc inc|cpp/container/dsc const_reference|vector}}
{{dcl list template | cpp/container/dcl list pointer | vector}}
+
{{dsc inc|cpp/container/dsc pointer|vector}}
{{dcl list template | cpp/container/dcl list const_pointer | vector}}
+
{{dsc inc|cpp/container/dsc const_pointer|vector}}
{{dcl list template | cpp/container/dcl list iterator | vector}}
+
{{dsc inc|cpp/container/dsc iterator|vector}}
{{dcl list template | cpp/container/dcl list const_iterator | vector}}
+
{{dsc inc|cpp/container/dsc const_iterator|vector}}
{{dcl list template | cpp/container/dcl list reverse_iterator | vector}}
+
{{dsc inc|cpp/container/dsc reverse_iterator|vector}}
{{dcl list template | cpp/container/dcl list const_reverse_iterator | vector}}
+
{{dsc inc|cpp/container/dsc const_reverse_iterator|vector}}
{{dcl list end}}
+
{{dsc end}}
  
 
===Member functions===
 
===Member functions===
{{dcl list begin}}
+
{{dsc begin}}
{{dcl list template | cpp/container/dcl list constructor | vector}}
+
{{dsc inc|cpp/container/dsc constructor|vector}}
{{dcl list template | cpp/container/dcl list destructor | vector}}
+
{{dsc inc|cpp/container/dsc destructor|vector}}
{{dcl list template | cpp/container/dcl list operator{{=}} | vector}}
+
{{dsc inc|cpp/container/dsc operator{{=}}|vector}}
{{dcl list template | cpp/container/dcl list assign | vector}}
+
{{dsc inc|cpp/container/dsc assign|vector}}
{{dcl list template | cpp/container/dcl list get_allocator | vector}}
+
{{dsc inc|cpp/container/dsc assign_range|vector}}
 +
{{dsc inc|cpp/container/dsc get_allocator|vector}}
  
{{dcl list h2 | Element access}}
+
{{dsc h2|Element access}}
{{dcl list template | cpp/container/dcl list at | vector}}
+
{{dsc inc|cpp/container/dsc at|vector}}
{{dcl list template | cpp/container/dcl list operator_at | vector}}
+
{{dsc inc|cpp/container/dsc operator_at|vector}}
{{dcl list template | cpp/container/dcl list front | vector}}
+
{{dsc inc|cpp/container/dsc front|vector}}
{{dcl list template | cpp/container/dcl list back | vector}}
+
{{dsc inc|cpp/container/dsc back|vector}}
{{dcl list template | cpp/container/dcl list data | vector}}
+
{{dsc inc|cpp/container/dsc data|vector}}
  
{{dcl list h2 | Iterators}}
+
{{dsc h2|Iterators}}
{{dcl list template | cpp/container/dcl list begin | vector}}
+
{{dsc inc|cpp/container/dsc begin|vector}}
{{dcl list template | cpp/container/dcl list end | vector}}
+
{{dsc inc|cpp/container/dsc end|vector}}
{{dcl list template | cpp/container/dcl list rbegin | vector}}
+
{{dsc inc|cpp/container/dsc rbegin|vector}}
{{dcl list template | cpp/container/dcl list rend | vector}}
+
{{dsc inc|cpp/container/dsc rend|vector}}
  
{{dcl list h2 | Capacity}}
+
{{dsc h2|Capacity}}
{{dcl list template | cpp/container/dcl list empty | vector}}
+
{{dsc inc|cpp/container/dsc empty|vector}}
{{dcl list template | cpp/container/dcl list size | vector}}
+
{{dsc inc|cpp/container/dsc size|vector}}
{{dcl list template | cpp/container/dcl list max_size | vector}}
+
{{dsc inc|cpp/container/dsc max_size|vector}}
{{dcl list template | cpp/container/dcl list reserve | vector}}
+
{{dsc inc|cpp/container/dsc reserve|vector}}
{{dcl list template | cpp/container/dcl list capacity | vector}}
+
{{dsc inc|cpp/container/dsc capacity|vector}}
{{dcl list template | cpp/container/dcl list shrink_to_fit | vector}}
+
{{dsc inc|cpp/container/dsc shrink_to_fit|vector}}
  
{{dcl list h2 | Modifiers}}
+
{{dsc h2|Modifiers}}
{{dcl list template | cpp/container/dcl list clear | vector}}
+
{{dsc inc|cpp/container/dsc clear|vector}}
{{dcl list template | cpp/container/dcl list insert | vector}}
+
{{dsc inc|cpp/container/dsc insert|vector}}
{{dcl list template | cpp/container/dcl list emplace | vector}}
+
{{dsc inc|cpp/container/dsc insert_range|vector}}
{{dcl list template | cpp/container/dcl list erase | vector}}
+
{{dsc inc|cpp/container/dsc emplace|vector}}
{{dcl list template | cpp/container/dcl list push_back | vector}}
+
{{dsc inc|cpp/container/dsc erase|vector}}
{{dcl list template | cpp/container/dcl list emplace_back | vector}}
+
{{dsc inc|cpp/container/dsc push_back|vector}}
{{dcl list template | cpp/container/dcl list pop_back | vector}}
+
{{dsc inc|cpp/container/dsc emplace_back|vector}}
{{dcl list template | cpp/container/dcl list resize | vector}}
+
{{dsc inc|cpp/container/dsc append_range|vector}}
{{dcl list template | cpp/container/dcl list swap | vector}}
+
{{dsc inc|cpp/container/dsc pop_back|vector}}
{{dcl list end}}
+
{{dsc inc|cpp/container/dsc resize|vector}}
 +
{{dsc inc|cpp/container/dsc swap|vector}}
 +
{{dsc end}}
  
 
===Non-member functions===
 
===Non-member functions===
{{dcl list begin}}
+
{{dsc begin}}
{{dcl list template | cpp/container/dcl list operator_cmp | vector}}
+
{{dsc inc|cpp/container/dsc operator_cmp|vector}}
{{dcl list template | cpp/container/dcl list swap2 | vector}}
+
{{dsc inc|cpp/container/dsc swap2|vector}}
{{dcl list end}}
+
{{dsc inc|cpp/container/dsc erase seq|vector}}
 +
{{dsc end}}
 +
 
 +
{{rrev|since=c++17|
 +
==={{rl|deduction guides|Deduction guides}}===
 +
}}
 +
 
 +
===Notes===
 +
{{ftm begin|std=1|comment=1}}
 +
{{ftm|__cpp_lib_containers_ranges|value=202202L|std=C++23|Ranges construction and insertion for containers}}
 +
{{ftm end}}
 +
 
 +
===Example===
 +
{{example
 +
|code=
 +
#include <iostream>
 +
#include <vector>
 +
 
 +
int main()
 +
{
 +
    // Create a vector containing integers
 +
    std::vector<int> v = {8, 4, 5, 9};
 +
 +
    // Add two more integers to vector
 +
    v.push_back(6);
 +
    v.push_back(9);
 +
   
 +
    // Overwrite element at position 2
 +
    v[2] = -1;
 +
 +
    // Print out the vector
 +
    for (int n : v)
 +
        std::cout << n << ' ';
 +
    std::cout << '\n';
 +
}
 +
|output=
 +
8 4 -1 9 6 9
 +
}}
 +
 
 +
===Defect reports===
 +
{{dr list begin}}
 +
{{dr list item|wg=lwg|dr=69|std=C++98|before=contiguity of the storage for elements of {{tt|vector}} was not required|after=required}}
 +
{{dr list item|wg=lwg|dr=230|std=C++98|before={{tt|T}} was not required to be {{named req|CopyConstructible}}<br>(an element of type {{tt|T}} might not be able to be constructed)|after={{tt|T}} is also required to<br>be {{named req|CopyConstructible}}}}
 +
{{dr list item|wg=lwg|dr=464|std=C++98|before=access to the underlying storage of an empty {{tt|vector}} resulted in UB|after={{tt|data}} function provided}}
 +
{{dr list end}}
 +
 
 +
===See also===
 +
{{dsc begin}}
 +
{{dsc inc|cpp/container/dsc inplace_vector}}
 +
{{dsc inc|cpp/container/dsc array}}
 +
{{dsc inc|cpp/container/dsc deque}}
 +
{{dsc end}}
  
[[de:cpp/container/vector]]
+
{{langlinks|cs|de|es|fr|it|ja|ko|pl|pt|ru|zh}}
[[es:cpp/container/vector]]
+
[[fr:cpp/container/vector]]
+
[[it:cpp/container/vector]]
+
[[ja:cpp/container/vector]]
+
[[pt:cpp/container/vector]]
+
[[ru:cpp/container/vector]]
+
[[zh:cpp/container/vector]]
+

Latest revision as of 21:20, 2 August 2024

 
 
 
 
Defined in header <vector>
template<

    class T,
    class Allocator = std::allocator<T>

> class vector;
(1)
namespace pmr {

    template< class T >
    using vector = std::vector<T, std::pmr::polymorphic_allocator<T>>;

}
(2) (since C++17)
1) std::vector is a sequence container that encapsulates dynamic size arrays.
2) std::pmr::vector is an alias template that uses a polymorphic allocator.

The elements are stored contiguously, which means that elements can be accessed not only through iterators, but also using offsets to regular pointers to elements. 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.

The storage of the vector is handled automatically, being expanded 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()[1].

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.

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).

std::vector (for T other than bool) meets the requirements of Container, AllocatorAwareContainer(since C++11), SequenceContainer, ContiguousContainer(since C++17) and ReversibleContainer.

Member functions of std::vector are constexpr: it is possible to create and use std::vector objects in the evaluation of a constant expression.

However, std::vector objects generally cannot be constexpr, because any dynamically allocated storage must be released in the same evaluation of constant expression.

(since C++20)
  1. In libstdc++, shrink_to_fit() is not available in C++98 mode.

Contents

[edit] Template parameters

T - The type of the elements.
T must meet the requirements of CopyAssignable and CopyConstructible. (until C++11)
The requirements that are imposed on the elements depend on the actual operations performed on the container. Generally, it is required that element type is a complete type and meets the requirements of Erasable, but many member functions impose stricter requirements. (since C++11)
(until C++17)

The requirements that are imposed on the elements depend on the actual operations performed on the container. Generally, it is required that element type meets the requirements of Erasable, but many member functions impose stricter requirements. This container (but not its members) can be instantiated with an incomplete element type if the allocator satisfies the allocator completeness requirements.

Feature-test macro Value Std Feature
__cpp_lib_incomplete_container_elements 201505L (C++17) Minimal incomplete type support
(since C++17)

[edit]

Allocator - An allocator that is used to acquire/release memory and to construct/destroy the elements in that memory. The type must meet the requirements of Allocator. The behavior is undefined(until C++20)The program is ill-formed(since C++20) if Allocator::value_type is not the same as T.[edit]

[edit] Specializations

The standard library provides a specialization of std::vector for the type bool, which may be optimized for space efficiency.

space-efficient dynamic bitset
(class template specialization) [edit]

[edit] Iterator invalidation

Operations Invalidated
All read only operations Never.
swap, std::swap end()
clear, operator=, assign Always.
reserve, shrink_to_fit If the vector changed capacity, all of them. If not, none.
erase Erased elements and all elements after them (including end()).
push_back, emplace_back If the vector changed capacity, all of them. If not, only end().
insert, emplace If the vector changed capacity, all of them.
If not, only those at or after the insertion point (including end()).
resize If the vector changed capacity, all of them. If not, only end() and any elements erased.
pop_back The element erased and end().

[edit] Member types

Member type Definition
value_type T[edit]
allocator_type Allocator[edit]
size_type Unsigned integer type (usually std::size_t)[edit]
difference_type Signed integer type (usually std::ptrdiff_t)[edit]
reference value_type&[edit]
const_reference const value_type&[edit]
pointer

Allocator::pointer

(until C++11)

std::allocator_traits<Allocator>::pointer

(since C++11)
[edit]
const_pointer

Allocator::const_pointer

(until C++11)

std::allocator_traits<Allocator>::const_pointer

(since C++11)
[edit]
iterator

LegacyRandomAccessIterator and LegacyContiguousIterator to value_type

(until C++20)

LegacyRandomAccessIterator, contiguous_iterator, and ConstexprIterator to value_type

(since C++20)
[edit]
const_iterator

LegacyRandomAccessIterator and LegacyContiguousIterator to const value_type

(until C++20)

LegacyRandomAccessIterator, contiguous_iterator, and ConstexprIterator to const value_type

(since C++20)
[edit]
reverse_iterator std::reverse_iterator<iterator>[edit]
const_reverse_iterator std::reverse_iterator<const_iterator>[edit]

[edit] Member functions

constructs the vector
(public member function) [edit]
destructs the vector
(public member function) [edit]
assigns values to the container
(public member function) [edit]
assigns values to the container
(public member function) [edit]
assigns a range of values to the container
(public member function) [edit]
returns the associated allocator
(public member function) [edit]
Element access
access specified element with bounds checking
(public member function) [edit]
access specified element
(public member function) [edit]
access the first element
(public member function) [edit]
access the last element
(public member function) [edit]
direct access to the underlying contiguous storage
(public member function) [edit]
Iterators
returns an iterator to the beginning
(public member function) [edit]
(C++11)
returns an iterator to the end
(public member function) [edit]
returns a reverse iterator to the beginning
(public member function) [edit]
(C++11)
returns a reverse iterator to the end
(public member function) [edit]
Capacity
checks whether the container is empty
(public member function) [edit]
returns the number of elements
(public member function) [edit]
returns the maximum possible number of elements
(public member function) [edit]
reserves storage
(public member function) [edit]
returns the number of elements that can be held in currently allocated storage
(public member function) [edit]
reduces memory usage by freeing unused memory
(public member function) [edit]
Modifiers
clears the contents
(public member function) [edit]
inserts elements
(public member function) [edit]
inserts a range of elements
(public member function) [edit]
(C++11)
constructs element in-place
(public member function) [edit]
erases elements
(public member function) [edit]
adds an element to the end
(public member function) [edit]
constructs an element in-place at the end
(public member function) [edit]
adds a range of elements to the end
(public member function) [edit]
removes the last element
(public member function) [edit]
changes the number of elements stored
(public member function) [edit]
swaps the contents
(public member function) [edit]

[edit] Non-member functions

(removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(C++20)
lexicographically compares the values of two vectors
(function template) [edit]
specializes the std::swap algorithm
(function template) [edit]
erases all elements satisfying specific criteria
(function template) [edit]

Deduction guides

(since C++17)

[edit] Notes

Feature-test macro Value Std Feature
__cpp_lib_containers_ranges 202202L (C++23) Ranges construction and insertion for containers

[edit] Example

#include <iostream>
#include <vector>
 
int main()
{
    // Create a vector containing integers
    std::vector<int> v = {8, 4, 5, 9};
 
    // Add two more integers to vector
    v.push_back(6);
    v.push_back(9);
 
    // Overwrite element at position 2
    v[2] = -1;
 
    // Print out the vector
    for (int n : v)
        std::cout << n << ' ';
    std::cout << '\n';
}

Output:

8 4 -1 9 6 9

[edit] Defect reports

The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

DR Applied to Behavior as published Correct behavior
LWG 69 C++98 contiguity of the storage for elements of vector was not required required
LWG 230 C++98 T was not required to be CopyConstructible
(an element of type T might not be able to be constructed)
T is also required to
be CopyConstructible
LWG 464 C++98 access to the underlying storage of an empty vector resulted in UB data function provided

[edit] See also

dynamically-resizable, fixed capacity, inplace contiguous array
(class template) [edit]
(C++11)
fixed-sized inplace contiguous array
(class template) [edit]
double-ended queue
(class template) [edit]