Array是container class array<>的一个实例,是一个固定长度的元素序列。ios
在使用array以前,须要include头文件:函数
#include <array>
// all elements of x have value 0 (int()) array<int,4> x = {}; //use an initializer list to initialize array array<int,5> coll = { 42, 377, 611, 21, 44 }; // one element with value 42, followed by 9 elements with value 0 array<int,10> c2 = { 42 };
Operation | Effect |
array<Elem, N> c | 默认构造函数:使用默认初始化元素建立一个array |
array<Elem, N> c(c2) | 复制构造函数:经过复制建立一个相同的array(全部元素都被复制) |
array<Elem, N> c = c2 | 复制构造函数:经过复制建立一个相同的array(全部元素都被复制) |
array<Elem, N> c(rv) | Move constructor:creates a new array taking the contents of the rvalue rv |
array<Elem, N> c = rv | Move constructor:creates a new array taking the contents of the rvalue rv |
array<Elem, N> c = initList | Creates an array initialized with the elements of the initializer list |
Operation | Effect |
c.empty() | 返回容器是否为空(至关于size() == 0) |
c.size() | 返回当前元素的个数 |
c.max_size() | 返回可能存在元素的最大个数 |
c1 == c2 | 返回c1是否等于c2 |
c1 != c2 | 返回c1是否不等于c2 |
c1 < c2 | 返回c1是否小于c2 |
c1 > c2 | 返回c1是否大于c2 |
c1 <= c2 | 返回c1是否小于等于c2 |
c1 >= c2 | 返回c1是否大于等于c2 |
Operation | Effect |
c = c2 | 将c2全部的元素赋给c |
c = rv | Move assigns all elements of the rvalue rv to c |
c.fill(val) | 将值val赋给c的每个元素 |
c1.swap(c2) | 交换c1和c2的数据 |
swap(c1, c2) | 交换c1和c2的数据 |
Operation | Effect |
c[idx] | 返回索引为idx的元素(没有边界检查) |
c.at(idx) | 返回索引为idx的元素(当idx超出边界,抛出range-error异常) |
c.front() | 返回第一个元素(不检查第一个元素是否存在) |
c.back() | 返回最后一个元素(不检查最后一个元素是否存在) |
Operation | Effect |
c.begin() | 返回第一个元素的随机访问迭代器 |
c.end() | 返回位于最后一个元素以后的随机访问迭代器 |
c.cbegin() | 返回第一个元素的常量随机存取迭代器 |
c.cend() | 返回位于最后一个元素以后的常量随机访问迭代器 |
c.rbegin() | 返回反向迭代器,指向最后一个元素 |
c.rend() | 返回反向迭代器,位于第一个元素以前 |
c.crbegin() | 返回常量反向迭代器,指向最后一个元素 |
c.crend() | 返回常量反向迭代器,位于第一个元素以前 |
Array提供了tuple 接口,因此:spa
例:code
typedef std::array<std::string, 5> FileStrings; FiveStrings a = {"hello", "nico", "how", "are", "you"}; std::tuple_size<FiveStrings>::value // 5 std::tuple_element<1, FiveStrings>::type // std::string std::get<1>(a) // std::string("nico")
#include <array> #include <algorithm> #include <functional> #include <numeric> #include "print.hpp" using namespace std; int main() { //create array with 10 ints array<int, 10> a = {11, 22, 33, 44 }; PRINT_ELEMENTS(a); //modify last two elements a.back() = 9999999; a[a.size() - 2] = 42; PRINT_ELEMENTS(a); //process sum of all elements cout<< "sum: " << accumulate(a.begin(), a.end(), 0) << endl; //negate all elements transform(a.begin(), a.end(), //source a.begin(), //destinatic negate<int>()); //operation PRINT_ELEMENTS(a); } // print.hpp #include<iostream> #include<string> //PRINT_ELEMENTS() // - prints optional string optstr followed by // - all elements of the collection coll // - in one line,separated by spaces template <typename T> inline void PRINT_ELEMENTS(const T& coll, const std::string& optstr="") { std::cout << optstr; for(const auto& elem : coll) { std::cout << elem << ' '; } std::cout << std::endl; }
输出:orm