https://en.cppreference.com/w/cpp/container
- 头文件
<array>
- 声明
template<
class T,
std::size_t N
> struct array;
- 描述
std::array 是一个容器,它封装了固定大小的数组。
这个容器是与C风格的数组T[N]具有相同的语义结构的集合类型。与C风格数组不同的是,它不能直接自动变成T*。作为一个集合类型,它可以由集合进行初始化: std::array<int, 3> a = {1,2,3};.
这个结构结合了C风格的高性能和方便性和标准容器收益,例如,知道它的大小、它支持的赋值、随机访问iterators,等等。
一个特殊情况,数组大小为0.这种情况下,array.begin() == array.end(),且是某个唯一值。对0大小的数组进行front()或back()的调用结果未定义。
- 迭代
值得说明的是,在“swap”期间,迭代器会继续指向相同的数组元素,并改变它的值。
- 成员类型
类型 | 定义 |
value_type | T |
size_type | std::size_t |
difference_type | std::ptrdiff_t |
reference | value_type& |
const_reference | const value_type& |
pointer | value_type* |
const_pointer | const value_type* |
iterator | legacyRandomAccessIterator and ConstexprIterator (since C++20)that is a LiteralType (since C++17) |
const_iterator | Constant LegacyRandomAccessIterator and ConstexprIterator (since C++20)that is a LiteralType (since C++17) |
reverse_iterator | std::reverse_iterator<iterator> |
const_reverse_iterator | std::reverse_iterator<const_iterator> |
- 成员操作
元素访问
at | access specified element with bounds checking (public member function) |
operator[] | access specified element (public member function) |
front | access the first element (public member function) |
back | access the last element (public member function) |
data | direct access to the underlying array (public member function).获取数组的数据存放的内存地址 |
迭代器
begin cbegin | returns an iterator to the beginning (public member function) |
end cend | returns an iterator to the end (public member function) |
rbegin crbegin | returns a reverse iterator to the beginning (public member function) |
指标相关操作
empty | checks whether the container is empty (public member function) |
size | returns the number of elements (public member function) |
max_size | returns the maximum possible number of elements (public member function) |
数值操作
fill | void fill( const T& value ); | fill the container with specified value (public member function) |
swap | void swap( array& other ) noexcept(/* see below */); | swaps the contents (public member function) |
- 举例
#include <string>
#include <iterator>
#include <iostream>
#include <algorithm>
#include <array>
int main()
{
// construction uses aggregate initialization
std::array<int, 3> a1{ {1, 2, 3} }; // double-braces required in C++11 prior to the CWG 1270 revision
// (not needed in C++11 after the revision and in C++14 and beyond)
std::array<int, 3> a2 = {1, 2, 3}; // never required after =
std::array<std::string, 2> a3 = { std::string("a"), "b" };
// container operations are supported
std::sort(a1.begin(), a1.end());
std::reverse_copy(a2.begin(), a2.end(),
std::ostream_iterator<int>(std::cout, " "));
std::cout << '\n';
// ranged for loop is supported
for(const auto& s: a3)
std::cout << s << ' ';
}
Output:
3 2 1
a b