class template
std::array
🔙返回目录(建议收藏):全面理解C++ STL标准模板库
[array目录]
1. 什么是array
template <class T, size_t N> class array;
array是固定大小
的序列容器,它们包含按严格线性序列
排序的特定数量的元素。
2. array的定义
std::array<int,3> myarray = {5, 19, 77};
3. array成员函数
3.1 迭代器
迭代器 | 功能 |
---|---|
begin | Return iterator to beginning |
end | Return iterator to end |
rbegin | Return reverse iterator to reverse beginning |
rend | Return reverse iterator to reverse end |
cbegin | Return const_iterator to beginning |
cend | Return const_iterator to end |
crbegin | Return const_reverse_iterator to reverse beginning |
crend | Return const_reverse_iterator to reverse end |
举个例子
// array::begin example
#include <iostream>
#include <array>
int main ()
{
std::array<int,5> myarray = { 2, 16, 77, 34, 50 };
std::cout << "myarray contains:";
for ( auto it = myarray.begin(); it != myarray.end(); ++it )
std::cout << ' ' << *it;
std::cout << '\n';
return 0;
}
Output:
myarray contains: 2 16 77 34 50
3.2 array容量
容量 | 功能 |
---|---|
size | Return size |
max_size | Return maximum size |
empty | Test whether array is empty |
举个例子
// array::size
#include <iostream>
#include <array>
int main ()
{
std::array<int,5> myints;
std::cout << "size of myints: " << myints.size() << std::endl;
std::cout << "sizeof(myints): " << sizeof(myints) << std::endl;
return 0;
}
Possible output:
size of myints: 5
sizeof(myints): 20
3.3 元素访问
访问函数 | 功能 |
---|---|
[] | Access element |
at | Access element |
front | Access first element |
back | Access last element |
data | Get pointer to data |
举个例子
// array::front
#include <iostream>
#include <array>
int main ()
{
std::array<int,3> myarray = {2, 16, 77};
std::cout << "front is: " << myarray.front() << std::endl; // 2
std::cout << "back is: " << myarray.back() << std::endl; // 77
myarray.front() = 100;
std::cout << "myarray now contains:";
for ( int& x : myarray ) std::cout << ' ' << x;
std::cout << '\n';
return 0;
}
3.4 修饰函数
成员函数 | 功能 |
---|---|
fill | Fill array with value |
swap | Swap content |
// swap arrays
#include <iostream>
#include <array>
int main ()
{
std::array<int,5> first = {10, 20, 30, 40, 50};
std::array<int,5> second = {11, 22, 33, 44, 55};
first.swap (second);
std::cout << "first:";
for (int& x : first) std::cout << ' ' << x;
std::cout << '\n';
std::cout << "second:";
for (int& x : second) std::cout << ' ' << x;
std::cout << '\n';
return 0;
}
Output:
first: 11 22 33 44 55
second: 10 20 30 40 50