Arrays are familiar to everyone, vectors are often used by us.
However, in some cases, the use of vectors is superfluous, especially the number of elements can be defined in the case, so we pay a lower cost of efficiency!
But the cost of using arrays is so insecure, so inconvenient.
As a result, C++11 introduced the template class array, which is located in the STD name control.
Unlike vectors, the length of an array object is fixed, using a static storage area, which is stored on the stack, with the same efficiency as the array, but more secure.
You first need to include the header file array, and the syntax differs from vector:
#include<array>...std::array<int,5> ai;//创建一个有5个int成员的对象std::array<double,4> ad = {1.22.13.14.1};
By the way, C++11 allows you to assign values to Vetcor and arrays using the initialization list, see the blog "Initializer_list of C++11 features" for details
Personally, the biggest advantage of array over arrays is that you can assign an array object to another array object:
std::array<double, 4> ad = {1.22.13.14.1};std::array<double, 4> ad1;ad1 = ad;
Array index out of bounds is also the pit we often hide, arrays and vectors do not check the correctness of index values when using the brackets index.
However, they have a member function that can be indexed in place of brackets so that the bounds are checked:
std::array<double, 4> ad = {1.22.13.14.1};ad[-20.5;//合法ad.at(11.1;
With at (), an illegal index is captured during the run, and the program is interrupted by default.
Last paragraph of the Code:
#include <string>#include <iterator>#include <iostream>#include <algorithm>#include <array>intMain () {//Construction uses aggregate initialization STD:: Array<int, 5>i_array1{{3,4,5,1,2} };//double-braces required STD:: Array<int, 5>I_array2 = {1,2,3,4,5};//Except after = STD:: Array<std::string, 2>String_array = {{STD::string("a"),"B"} };STD::cout<<"Initial i_array1:"; for(AutoI:I_ARRAY1)STD::cout<< I <<"';//container operations is supported STD:: Sort (I_array1.begin (), I_array1.end ());STD::cout<<"\nsored i_array1:"; for(AutoI:I_ARRAY1)STD::cout<< I <<"';STD::cout<<"\ninitial i_array2:"; for(AutoI:I_ARRAY2)STD::cout<< I <<"';STD::cout<<"\nreversed i_array2:";STD:: Reverse_copy (I_array2.begin (), I_array2.end (),STD::ostream_iterator<int> (STD::cout," "));//ranged for loop is supported STD::cout<<"\nstring_array:"; for(Auto& S:string_array)STD::cout<< s <<"';return 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
The Std::array of c++11 new features container