Przejdź do głównej zawartości

Defined in: <array>

Overview

template <typename T, std::size_t N>
class array

std::array is a container that encapsulates fixed size arrays. It is a safer alternative to C-style arrays - T arr[N].

Example usage

The examples in this section are very simple ones. Navigate to examples section at the bottom for more.

To create an array with an automatically deduced size or/and type, we can use std::to_array (since C++20).
Note: type and size deduction (at the same time) was possible since C++17.

#include <array>

int main() {
// type: std::array<int, 4>
auto ints = std::to_array({1, 5, 3, 7});
// type: std::array<float, 4>
auto floats = std::to_array<float>({1, 5, 3, 7});
// type: std::array<char, 6>
auto hello = std::to_array("Hello");
// this is different to std::array{"Hello"}, which creates std::array<char const*, 1>
}

Memory

The elements of an array are stored contiguously in memory.

Technical details

Technical definition of an array

This container is an aggregate type with the same semantics as a struct holding a C-style array T[N] as its only non-static data member. Unlike a C-style array, it doesn't decay to T* automatically. As an aggregate type, it can be initialized with aggregate-initialization given at most N initializers that are convertible to T:

std::array<int, 3> a = {1,2,3};

The struct combines the performance and accessibility of a C-style array with the benefits of a standard container, such as knowing its own size, supporting assignment, random access iterators, etc.

An array can also be used as a tuple of N elements of the same type.

Zero-length array (N == 0)

There is a special case for a zero-length array (N == 0). In that case, array.begin() == array.end(), which is some unique value. The effect of calling front() or back() on a zero-sized array is undefined.

Named requirements

std::array satisfies the requirements of:

except that default-constructed array is not empty and that the complexity of swapping is linear

Satisfies the requirements of:

std::array

Defined inarray

Template parameters

pubTType of the elements
pubNNumber of elements (a compile-time constant)

Type names

pubvalue_typeT
pubsize_typestd::size_t
pubdifference_typestd::ptrdiff_t
pubreferencevalue_type&
pubconst_referencevalue_type const&
pubpointervalue_type*
pubconst_pointervalue_type const*
pubiteratorLegacyRandomAccessIterator to value_type
pubconst_iteratorLegacyRandomAccessIterator to value_type const
pubreverse_iteratorstd::reverse_iterator<iterator>
pubconst_reverse_iteratorstd::reverse_iterator<const_iterator>

Member functions

pub(constructor)Constructs an array following the rules of aggregate initialization.
pub(destructor)Destroys every element of the array.
puboperator=Overwrites every element of the array with the corresponding element of another array.

Element access

pubatAccesses the specified element with bounds checking.
puboperator[]Accesses the element.
pubfrontReturns the first element.
pubbackReturns the last element.
pubdataReturns a pointer to the first element of the underlying array.

Iterators

pubbegin
cbegin
Returns an iterator/const_iterator to the beginning.
pubend
cend
Returns an iterator/const_iterator to the end.
pubrbegin
crbegin
Returns a reverse iterator/const_iterator to the beginning.
pubrend
crend
Returns a reverse iterator/const_iterator to the end.

Capacity

pubemptyReturns true if the container is empty, otherwise false.
pubsizeReturns the number of elements.
pubmax_sizeReturns the maximum possible number of elements.

Operations

pubfillFills the container with specified value.
pubswapSwaps the contents.

Non-member functions

puboperator==
operator!=
operator<
operator>
operator<=
operator>=
operator<=>
Lexicographically compares the values in the array.
pubstd::get (std::array)Accesses an element of the array.
pubstd::swap (std::array)Specializes the std::swap algorithm.
pubstd::to_array (C++20)Creates a std::array object from a built-in array.

Helper classes

pubstd::tuple_size<std::array> (C++11)
Obtains the size of an array.
pubstd::tuple_element<std::array> (C++11)
Obtains the type of the elements of an array.

Deduction guides (since C++17)

Click to expand

Deduction guides

// (1)
template< class T, class... U >
array( T, U... ) -> array<T, 1 + sizeof...(U)>;

(1) allows deduction from a variadic parameter pack

It's purpose is to provide an equivalent of std::experimental::make_array.

The program is ill-formed if any U is not the same as T (std::is_same_v<T, U> && ...).

An empty parameter pack is allowed, the type of std::array is std::array<T, 1> then.

More examples

Using algorithms

Find minimal value (C++20)
#include <iostream>
#include <array>
#include <algorithm>

int main()
{
namespace rg = std::ranges;

auto numbers = std::to_array({ 12, 3, 18, 9});

// Find minimal element
auto minIt = rg::min_element(numbers);

// obtain value:
auto value = *minIt;
// find position:
auto index = std::distance(numbers.begin(), minIt);


std::cout << "Min: " << value
<< ", at index: " << index
<< std::endl;
}
Result
Min: 3, at index: 1

Advanced

Using array as a temporary buffer
#include <fstream>
#include <array>
#include <string>

std::string readFile(std::istream& file)
{
constexpr size_t BUFFER_SIZE = 16 * 1024; // 16 KB
constexpr size_t RESERVE_SIZE = 1 * 1024 * 1024; // 1 MB
std::string result;
result.reserve(RESERVE_SIZE); // 1 MB

std::array<char, BUFFER_SIZE> buf;

while(file.read(buf.data(), buf.size()))
result.append(buf.data(), buf.data() + file.gcount());

result.append(buf.data(), buf.data() + file.gcount());
return result;
}

// Example usage:
int main()
{
std::ifstream file("hello.txt");
if (file.is_open())
{
auto fileContents = readFile(file);
// ...
}
}
Concat two arrays (C++20)
#include <iostream>
#include <array>
#include <algorithm>

template <typename T, size_t N1, size_t N2>
auto concat(
std::array<T, N1> const& lhs,
std::array<T, N2> const& rhs
)
{
namespace rg = std::ranges;

std::array<T, N1 + N2> result;

rg::copy(lhs, result.begin());
rg::copy_backward(rhs, result.end());

return result;
}

int main()
{
auto left = std::to_array({1, 2, 3});
auto right = std::to_array({4, 5, 6});

auto both = concat(left, right);

for (int elem : both)
std::cout << elem << ' ';
}
Result
1 2 3 4 5 6
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: <array>

Overview

template <typename T, std::size_t N>
class array

std::array is a container that encapsulates fixed size arrays. It is a safer alternative to C-style arrays - T arr[N].

Example usage

The examples in this section are very simple ones. Navigate to examples section at the bottom for more.

To create an array with an automatically deduced size or/and type, we can use std::to_array (since C++20).
Note: type and size deduction (at the same time) was possible since C++17.

#include <array>

int main() {
// type: std::array<int, 4>
auto ints = std::to_array({1, 5, 3, 7});
// type: std::array<float, 4>
auto floats = std::to_array<float>({1, 5, 3, 7});
// type: std::array<char, 6>
auto hello = std::to_array("Hello");
// this is different to std::array{"Hello"}, which creates std::array<char const*, 1>
}

Memory

The elements of an array are stored contiguously in memory.

Technical details

Technical definition of an array

This container is an aggregate type with the same semantics as a struct holding a C-style array T[N] as its only non-static data member. Unlike a C-style array, it doesn't decay to T* automatically. As an aggregate type, it can be initialized with aggregate-initialization given at most N initializers that are convertible to T:

std::array<int, 3> a = {1,2,3};

The struct combines the performance and accessibility of a C-style array with the benefits of a standard container, such as knowing its own size, supporting assignment, random access iterators, etc.

An array can also be used as a tuple of N elements of the same type.

Zero-length array (N == 0)

There is a special case for a zero-length array (N == 0). In that case, array.begin() == array.end(), which is some unique value. The effect of calling front() or back() on a zero-sized array is undefined.

Named requirements

std::array satisfies the requirements of:

except that default-constructed array is not empty and that the complexity of swapping is linear

Satisfies the requirements of:

std::array

Defined inarray

Template parameters

pubTType of the elements
pubNNumber of elements (a compile-time constant)

Type names

pubvalue_typeT
pubsize_typestd::size_t
pubdifference_typestd::ptrdiff_t
pubreferencevalue_type&
pubconst_referencevalue_type const&
pubpointervalue_type*
pubconst_pointervalue_type const*
pubiteratorLegacyRandomAccessIterator to value_type
pubconst_iteratorLegacyRandomAccessIterator to value_type const
pubreverse_iteratorstd::reverse_iterator<iterator>
pubconst_reverse_iteratorstd::reverse_iterator<const_iterator>

Member functions

pub(constructor)Constructs an array following the rules of aggregate initialization.
pub(destructor)Destroys every element of the array.
puboperator=Overwrites every element of the array with the corresponding element of another array.

Element access

pubatAccesses the specified element with bounds checking.
puboperator[]Accesses the element.
pubfrontReturns the first element.
pubbackReturns the last element.
pubdataReturns a pointer to the first element of the underlying array.

Iterators

pubbegin
cbegin
Returns an iterator/const_iterator to the beginning.
pubend
cend
Returns an iterator/const_iterator to the end.
pubrbegin
crbegin
Returns a reverse iterator/const_iterator to the beginning.
pubrend
crend
Returns a reverse iterator/const_iterator to the end.

Capacity

pubemptyReturns true if the container is empty, otherwise false.
pubsizeReturns the number of elements.
pubmax_sizeReturns the maximum possible number of elements.

Operations

pubfillFills the container with specified value.
pubswapSwaps the contents.

Non-member functions

puboperator==
operator!=
operator<
operator>
operator<=
operator>=
operator<=>
Lexicographically compares the values in the array.
pubstd::get (std::array)Accesses an element of the array.
pubstd::swap (std::array)Specializes the std::swap algorithm.
pubstd::to_array (C++20)Creates a std::array object from a built-in array.

Helper classes

pubstd::tuple_size<std::array> (C++11)
Obtains the size of an array.
pubstd::tuple_element<std::array> (C++11)
Obtains the type of the elements of an array.

Deduction guides (since C++17)

Click to expand

Deduction guides

// (1)
template< class T, class... U >
array( T, U... ) -> array<T, 1 + sizeof...(U)>;

(1) allows deduction from a variadic parameter pack

It's purpose is to provide an equivalent of std::experimental::make_array.

The program is ill-formed if any U is not the same as T (std::is_same_v<T, U> && ...).

An empty parameter pack is allowed, the type of std::array is std::array<T, 1> then.

More examples

Using algorithms

Find minimal value (C++20)
#include <iostream>
#include <array>
#include <algorithm>

int main()
{
namespace rg = std::ranges;

auto numbers = std::to_array({ 12, 3, 18, 9});

// Find minimal element
auto minIt = rg::min_element(numbers);

// obtain value:
auto value = *minIt;
// find position:
auto index = std::distance(numbers.begin(), minIt);


std::cout << "Min: " << value
<< ", at index: " << index
<< std::endl;
}
Result
Min: 3, at index: 1

Advanced

Using array as a temporary buffer
#include <fstream>
#include <array>
#include <string>

std::string readFile(std::istream& file)
{
constexpr size_t BUFFER_SIZE = 16 * 1024; // 16 KB
constexpr size_t RESERVE_SIZE = 1 * 1024 * 1024; // 1 MB
std::string result;
result.reserve(RESERVE_SIZE); // 1 MB

std::array<char, BUFFER_SIZE> buf;

while(file.read(buf.data(), buf.size()))
result.append(buf.data(), buf.data() + file.gcount());

result.append(buf.data(), buf.data() + file.gcount());
return result;
}

// Example usage:
int main()
{
std::ifstream file("hello.txt");
if (file.is_open())
{
auto fileContents = readFile(file);
// ...
}
}
Concat two arrays (C++20)
#include <iostream>
#include <array>
#include <algorithm>

template <typename T, size_t N1, size_t N2>
auto concat(
std::array<T, N1> const& lhs,
std::array<T, N2> const& rhs
)
{
namespace rg = std::ranges;

std::array<T, N1 + N2> result;

rg::copy(lhs, result.begin());
rg::copy_backward(rhs, result.end());

return result;
}

int main()
{
auto left = std::to_array({1, 2, 3});
auto right = std::to_array({4, 5, 6});

auto both = concat(left, right);

for (int elem : both)
std::cout << elem << ' ';
}
Result
1 2 3 4 5 6
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.