Array 是一種大小固定的順序容器。array 的申明:
template <class T, size_t N>class array;
Array內(nèi)部只存儲所包含的數(shù)據(jù),哪怕是大小也只不過是個模板參數(shù)。和普通使用‘[]’語法申明的數(shù)組相比,只不過顯得更加高效(操作高效),因為這個類添加了一系列的全局成員函數(shù)用來操作這些元素。下面來列一些主要的操作:
// ‘[]’ 操作#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;}
運(yùn)行結(jié)果:
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 成員函數(shù):返回指向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;}
運(yùn)行結(jié)果:
C:\Windows\system32\cmd.exe /c array.exe
Test string
Hit any key to close this window...
// fill 函數(shù),設(shè)置array內(nèi)部的所有元素為指定值#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;}
運(yùn)行結(jié)果:
C:\Windows\system32\cmd.exe /c array.exe
myarray contains: 5 5 5 5 5 5
Hit any key to close this window...
// swap 函數(shù):交換兩個array的內(nèi)容,注意兩個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;}
運(yùn)行結(jié)果:
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...
本站僅提供存儲服務(wù),所有內(nèi)容均由用戶發(fā)布,如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請
點擊舉報。