C++ 11 array

Array 是一种大小固定的顺序容器。array 的申明:

template <class T, size_t N>
class array;
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...
 
 
// 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...
 
 
 
// 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...
 

 

posted @ 2012-08-02 22:54  KingsLanding  阅读(7028)  评论(0编辑  收藏  举报