數組每個人都很熟悉,vector更是我們常常用到的。
但是某些場合,使用vector是多余的,尤其能明確元素個數的情況下,這樣我們就付出了效率稍低的代價!
但是你使用數組的代價是那么的不安全,那么的不方便。
于是,C++11推出了模板類array,位于std名稱控件中。?
與vector不同的是,array對象的長度是固定的,使用了靜態存儲區,即存儲在棧上,效率跟數組相同,但是更加的安全。
首先需要包含頭文件array,而且語法與vector也有所不同:
~~~
#include<array>
...
std::array<int,5> ai;//創建一個有5個int成員的對象
std::array<double,4> ad = {1.2, 2.1, 3.1, 4.1};
~~~
順便提一嘴,C++11允許使用初始化列表對vetcor和array進行賦值,詳情請見博客《?[c++11特性之initializer_list](http://blog.csdn.net/wangshubo1989/article/details/49622871 "初始化列表")》
個人覺得array相比于數組最大的優勢就是可以將一個array對象賦值給另一個array對象:
~~~
std::array<double, 4> ad = {1.2, 2.1, 3.1, 4.1};
std::array<double, 4> ad1;
ad1 = ad;
~~~
數組索引越界也是我們往往躲不過的坑兒,array和vector使用中括號索引時也不會檢查索引值的正確性。
但是,他們有一個成員函數可以替代中括號進行索引,這樣越界就會進行檢查:
~~~
std::array<double, 4> ad = {1.2, 2.1, 3.1, 4.1};
ad[-2] = 0.5;//合法
ad.at(1) = 1.1;
~~~
使用at(),將在運行期間捕獲非法索引的,默認將程序中斷。
最后上一段代碼:
~~~
#include <string>
#include <iterator>
#include <iostream>
#include <algorithm>
#include <array>
int main()
{
// 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(auto i: i_array1)
std::cout << i << ' ';
// container operations are supported
std::sort(i_array1.begin(), i_array1.end());
std::cout << "\nsored i_array1 : ";
for(auto i: i_array1)
std::cout << i << ' ';
std::cout << "\nInitial i_array2 : ";
for(auto i: 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;
}
~~~
- 前言
- 吐血整理C++11新特性
- C++11新特性之std::function
- c++11特性之正則表達式
- c++11特性之Lambda表達式
- c++11特性之override和final關鍵字
- c++11特性之std::thread--初識
- c++11特性之std::thread--初識二
- c++11特性之initializer_list
- c++11特性之std::thread--進階
- c++11特性之std::thread--進階二
- C++11新特性之 CALLBACKS
- C++11新特性之 std::array container
- C++11新特性之 nullptr
- C++11新特性之 rvalue Reference(右值引用)
- C++11新特性之 Move semantics(移動語義)
- C++11新特性之 default and delete specifiers
- C++11新特性之 Static assertions 和constructor delegation
- 開始使用C++11的幾個理由
- C++11新特性之 std::future and std::async