Array 是一種大小固定的順序容器。array 的申明: template <class T, size_t N> class array; Array內(nèi)部只存儲(chǔ)所包含的數(shù)據(jù),哪怕是大小也只不過(guò)是個(gè)模板參數(shù)。和普通使用‘[]’語(yǔ)法申明的數(shù)組相比,只不過(guò)顯得更加高效(操作高效),因?yàn)檫@個(gè)類(lèi)添加了一系列的全局成員函數(shù)用來(lái)操作這些元素。下面來(lái)列一些主要的操作:
// ‘[]’ 操作 #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... 運(yùn)行結(jié)果:
C:\Windows\system32\cmd.exe /c array.exe
Test string Hit any key to close this window... 運(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ù):交換兩個(gè)array的內(nèi)容,注意兩個(gè)array必須是相同類(lèi)型,相同大小 #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...
|
|