感冒
转载来自:http://blog.csdn.net/rumswell/article/details/7338025
//在使用C语言或cpp创建数组时,大量使用new和delete,很不爽
//现在改用使用<array>,很方便,用起来和STL<vector>一样的
//执行效率比<vector>高,几乎和int myarray[5]效率一样
转载来自:http://www.cnblogs.com/zhuyp1015/archive/2012/08/02/2620767.html
Array 是一种大小固定的顺序容器。array 的申明:
template <class T, size_t N> class array;
// ‘[]’ 操作
#include <iostream>
#include <array>
int main ()
{
std::array<int,10> myarray;
unsigned int i;
// assign some values:
for (i=0; i<10; i++) myarray[i] = i * 10;
// print content
std::cout << "myarray contains:";
for(int &i : myarray)
std::cout << " " << i;
std::cout << std::endl;
return 0;
}
运行结果:
C:\Windows\system32\cmd.exe /c array.exe
myarray contains: 0 10 20 30 40 50 60 70 80 90
Hit any key to close this window...
Test string
Hit any key to close this window...
myarray contains: 0 10 20 30 40 50 60 70 80 90
Hit any key to close this window...
// data 成员函数:返回指向array第一个元素的指针
#include <iostream>
#include <cstring>
#include <array>
int main ()
{
const char* cstr = "Test string";
std::array<char,12> charray;
memcpy (charray.data(),cstr,12);
std::cout << charray.data() << std::endl;
return 0;
}
C:\Windows\system32\cmd.exe /c array.exe
Test string
Hit any key to close this window...
// fill 函数,设置array内部的所有元素为指定值
#include <iostream>
#include <array>
int main () {
std::array<int,6> myarray;
myarray.fill(5);
std::cout << "myarray contains:";
for ( int& x : myarray) { std::cout << " " << x; }
std::cout << std::endl;
return 0;
}
运行结果:
C:\Windows\system32\cmd.exe /c array.exe
myarray contains: 5 5 5 5 5 5
Hit any key to close this window...
myarray contains: 5 5 5 5 5 5
Hit any key to close this window...
// swap 函数:交换两个array的内容,注意两个array必须是相同类型,相同大小
#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 << std::endl;
std::cout << "second:";
for (int& x : second) std::cout << " " << x;
std::cout << std::endl;
return 0;
}
运行结果:
C:\Windows\system32\cmd.exe /c array.exe
first: 11 22 33 44 55
second: 10 20 30 40 50
Hit any key to close this window...
first: 11 22 33 44 55
second: 10 20 30 40 50
Hit any key to close this window...