Przejdź do głównej zawartości

Defined in: <vector>

Overview

template< typename T, /* ... */ >
class vector;

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() (od 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

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.

Allocator

The type must meet the requirements of Allocator.

The program is ill-formed if Allocator::value_type is not the same as T.

std::vector

Defined invector

Template parameters

See technical details for more detailed information.

pubTType of the elements.
pubAllocator

Allocator that is used to acquire/release memory and to construct/destroy the elements in that memory.

Type names

pubvalue_typeT
puballocator_typeAllocator
pubsize_typeUnsigned integer type (usually std::size_t)
pubdifference_typeSigned integer type (usually std::ptrdiff_t)
pubreferencevalue_type&
pubconst_referencevalue_type const&
pubpointerAllocator::pointer (do C++11)
std::allocator_traits<Allocator>::pointer (od C++11)
pubconst_pointerAllocator::const_pointer (do C++11)
std::allocator_traits<Allocator>::const_pointer (od C++11)
pubiterator

LegacyRandomAccessIterator and  LegacyContiguousIterator to value_type 

 (do C++20)

LegacyRandomAccessIterator and  LegacyConstexprIterator and  contiguous_iterator to value_type 

 (od C++20)
pubconst_iterator

LegacyRandomAccessIterator and  LegacyContiguousIterator to value_type 

 (do C++20)

LegacyRandomAccessIterator and  LegacyConstexprIterator and  contiguous_iterator to const value_type 

 (od C++20)
pubreverse_iteratorstd::reverse_iterator<iterator>
pubconst_reverse_iteratorstd::reverse_iterator<const_iterator>

Member functions

pub(constructors)

Constructs a vector.

pub(destructor)

Destroys the vector, deallocating internal storage if used.

puboperator=

Assigns values to the container.

pubassign

Assigns values to the container.

pubget_allocator

Returns the associated allocator.

Element access

pubat

Accesses a specified element with bounds checking.

puboperator[]

Accesses a specified element.

pubfront

Returns the first element.

pubback

Returns the last element.

pubdata

Returns a pointer to the first element of the underlying array.

Iterators

pub begin
cbegin  (od C++11)

Returns an iterator/const_iterator to the beginning.

pub end
cend  (od C++11)

Returns an iterator/const_iterator to the end.

pub rbegin
crbegin  (od C++11)

Returns a reverse iterator/const_iterator to the beginning.

pub rend
crend  (od C++11)

Returns a reverse iterator/const_iterator to the end.

Capacity

pubempty

Returns true if the vector is empty, otherwise false.

pubsize

Returns the number of elements.

pubmax_size

Returns the maximum possible number of elements.

pubreserve

Reserves storage.

pubcapacity

Returns the number of elements that can be held in currently allocated storage.

pubshrink_to_fit  (od C++11)

Reduces memory usage by freeing unused memory.

Operations

pubclear

Clears the contents.

pubinsert

Inserts elements.

pub emplace  (od C++11)

Constructs elements in-place.

puberase

Removes elements.

pubpush_back

Appends an element to the end.

pub emplace_back  (od C++11)

Constructs elements in-place at the end.

pubpop_back

Removes the last element.

pubresize

Changes the number of elements stored.

pubswap

Swaps the contents.

Non-member functions

puboperator==
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.

pubstd::swap (std::vector)

An overload for a std::swap algorithm.

puberase (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:

zanotuj

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:

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';
}
Result
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;
}
Result
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';
}
}
Result
Sad Crab
Happy Wolf
Wicked Witch
Crazy Clown
Funny Monkey
This article originates from this CppReference page. It was likely altered for improvements or editors' preference. Click "Edit this page" to see all changes made to this document.
Hover to see the original license.

Defined in: <vector>

Overview

template< typename T, /* ... */ >
class vector;

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() (od 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

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.

Allocator

The type must meet the requirements of Allocator.

The program is ill-formed if Allocator::value_type is not the same as T.

std::vector

Defined invector

Template parameters

See technical details for more detailed information.

pubTType of the elements.
pubAllocator

Allocator that is used to acquire/release memory and to construct/destroy the elements in that memory.

Type names

pubvalue_typeT
puballocator_typeAllocator
pubsize_typeUnsigned integer type (usually std::size_t)
pubdifference_typeSigned integer type (usually std::ptrdiff_t)
pubreferencevalue_type&
pubconst_referencevalue_type const&
pubpointerAllocator::pointer (do C++11)
std::allocator_traits<Allocator>::pointer (od C++11)
pubconst_pointerAllocator::const_pointer (do C++11)
std::allocator_traits<Allocator>::const_pointer (od C++11)
pubiterator

LegacyRandomAccessIterator and  LegacyContiguousIterator to value_type 

 (do C++20)

LegacyRandomAccessIterator and  LegacyConstexprIterator and  contiguous_iterator to value_type 

 (od C++20)
pubconst_iterator

LegacyRandomAccessIterator and  LegacyContiguousIterator to value_type 

 (do C++20)

LegacyRandomAccessIterator and  LegacyConstexprIterator and  contiguous_iterator to const value_type 

 (od C++20)
pubreverse_iteratorstd::reverse_iterator<iterator>
pubconst_reverse_iteratorstd::reverse_iterator<const_iterator>

Member functions

pub(constructors)

Constructs a vector.

pub(destructor)

Destroys the vector, deallocating internal storage if used.

puboperator=

Assigns values to the container.

pubassign

Assigns values to the container.

pubget_allocator

Returns the associated allocator.

Element access

pubat

Accesses a specified element with bounds checking.

puboperator[]

Accesses a specified element.

pubfront

Returns the first element.

pubback

Returns the last element.

pubdata

Returns a pointer to the first element of the underlying array.

Iterators

pub begin
cbegin  (od C++11)

Returns an iterator/const_iterator to the beginning.

pub end
cend  (od C++11)

Returns an iterator/const_iterator to the end.

pub rbegin
crbegin  (od C++11)

Returns a reverse iterator/const_iterator to the beginning.

pub rend
crend  (od C++11)

Returns a reverse iterator/const_iterator to the end.

Capacity

pubempty

Returns true if the vector is empty, otherwise false.

pubsize

Returns the number of elements.

pubmax_size

Returns the maximum possible number of elements.

pubreserve

Reserves storage.

pubcapacity

Returns the number of elements that can be held in currently allocated storage.

pubshrink_to_fit  (od C++11)

Reduces memory usage by freeing unused memory.

Operations

pubclear

Clears the contents.

pubinsert

Inserts elements.

pub emplace  (od C++11)

Constructs elements in-place.

puberase

Removes elements.

pubpush_back

Appends an element to the end.

pub emplace_back  (od C++11)

Constructs elements in-place at the end.

pubpop_back

Removes the last element.

pubresize

Changes the number of elements stored.

pubswap

Swaps the contents.

Non-member functions

puboperator==
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.

pubstd::swap (std::vector)

An overload for a std::swap algorithm.

puberase (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:

zanotuj

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:

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';
}
Result
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;
}
Result
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';
}
}
Result
Sad Crab
Happy Wolf
Wicked Witch
Crazy Clown
Funny Monkey
This article originates from this CppReference page. It was likely altered for improvements or editors' preference. Click "Edit this page" to see all changes made to this document.
Hover to see the original license.