美文网首页C++
std::array (c++11)

std::array (c++11)

作者: allenyang羊羊 | 来源:发表于2019-05-30 11:09 被阅读0次

std::array是具有固定大小的数组。支持快速随机访问。不能添加或删除元素
需要包含头的头文件文件 #include<array>
其用法比较简单,和vector很类似,这里简单描述下和vector使用不一样的地方。

定义

  • 定义时必须指定array的大小,因为大小是模板参数之一,不可忽略;
  • 定义时不能使用变量指定大小;
  • 可通过array构造新的array,可以使用{}构造;
  • 不可使用数组构造,
  array<int, 5> myarray = {1,2,3,4,5};
  array<int,5> otherarray = myarray;
  int b[5];
  array<int,5> otherarray2 = b;//编译报错,error: no viable conversion from 'int [5]' to 'array<int, 5>
  int c=5;
  array<int,5> otherarray3;//编译报错,error: non-type template argument is not a constant expression
  int d[c];//普通数组是可以支持用变量初始化大小,所以std::array有点鸡肋呀

访问

可通过下标运算符[]对元素进行操作,还可以通过at/front/back进行操作

  for (int i = 0; i < 5; i++)
  {
    cout << setw(10) << << myarray.at(i) << endl;
  }

遍历

可以通过正向和反向迭代器对元素进行遍历

  for (auto it = myarray.begin(); it != myarray.end();++it)
  {
    cout << *it << endl;
  }

挖坑记

  1. 尽量使用at方法来访问元素,因为运算符[]不会对索引值进行检查,像myarray[-1]是不会报错的。使用at(),将在运行期间捕获非法索引的,默认将程序中断。

STL:array/vector/list比较

Function array vector list
constructor no yes yes
destructor no yes yes
empty() yes yes yes
size() yes yes yes
resize() no yes yes
capacity() no yes no
reserve() no yes no
max_size() yes yes yes
erase() no yes yes
clear() no yes yes
operator= yes yes yes
operator< yes yes yes
operator== yes yes yes
operator[] yes yes no
at() yes yes no
front() yes yes yes
back() yes yes yes
ush_back() no yes yes
pop_back() no yes yes
assign() yes yes yes
insert() no yes yes
swap() yes yes yes
push_front() no no yes
pop_front() no no yes
merge() no no yes
remove() no no yes
remove_if() no no yes
reverse() no no yes
sort() no no yes
splice() no no yes
unique() no no yes

相关文章

网友评论

    本文标题:std::array (c++11)

    本文链接:https://www.haomeiwen.com/subject/uaudtctx.html