C ++中的数组类足够高效,并且知道自己的大小。
size()=返回数组的大小,即返回数组元素的数量。
max_size()=返回数组中元素的最大数量。
get(),,at()
operator [] =获取对数组元素的访问。
front()=返回数组的前元素。
back()=返回数组的最后一个元素。
empty()=如果数组大小为true,则返回true,否则返回false。
fill()=用特定值填充整个数组。
swap()=将一个数组的元素交换到另一个。
这是实现上述所有操作的示例-
#include<iostream> #include<array> using namespace std; int main() { array<int,4>a = {10, 20, 30, 40}; array<int,4>a1 = {50, 60, 70, 90}; cout << "The size of array is : "; //size of the array using size() cout << a.size() << endl; //数组中元素的最大数量 cout << "Maximum elements array can hold is : "; cout << a.max_size() << endl; // Printing array elements using at() cout << "The array elements are (using at()) : "; for ( int i=0; i<4; i++) cout << a.at(i) << " "; cout << endl; // Printing array elements using get() cout << "The array elements are (using get()) : "; cout << get<0>(a) << " " << get<1>(a) << " "<<endl; cout << "The array elements are (using operator[]) : "; for ( int i=0; i<4; i++) cout << a[i] << " "; cout << endl; //打印数组的第一个元素 cout << "First element of array is : "; cout << a.front() << endl; //打印数组的最后一个元素 cout << "Last element of array is : "; cout << a.back() << endl; cout << "The second array elements before swapping are : "; for (int i=0; i<4; i++) cout << a1[i] << " "; cout << endl; //交换a1值 a.swap(a1); //交换后打印第一和第二数组 cout << "The first array elements after swapping are : "; for (int i=0; i<4; i++) cout << a[i] << " "; cout << endl; cout << "The second array elements after swapping are : "; for (int i = 0; i<4; i++) cout << a1[i] << " "; cout << endl; //检查是否为空 a1.empty()? cout << "Array is empty": cout << "Array is not empty"; cout << endl; //用1填充数组 a.fill(1); //填充后显示数组 cout << "Array content after filling operation is : "; for ( int i = 0; i<4; i++) cout << a[i] << " "; return 0; }
输出结果
The size of array is : 4 Maximum elements array can hold is : 4 The array elements are (using at()) : 10 20 30 40 The array elements are (using get()) : 10 20 The array elements are (using operator[]) : 10 20 30 40 First element of array is : 10 Last element of array is : 40 The second array elements before swapping are : 50 60 70 90 The first array elements after swapping are : 50 60 70 90 The second array elements after swapping are : 10 20 30 40 Array is not empty Array content after filling operation is : 1 1 1 1