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...
 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM