C++ 中 std::vector 和 std::array 的區別
下面是 vector 和 array 的區別 -
- Vector 是儲存元素的順序容器,而不是基於索引。
- Array 儲存相同型別元素的定長順序集合,並且它是基於索引的。
- Vector 的本質是動態的,因此大小會隨著元素的插入而增加。
- 由於陣列是定長,因此一旦初始化就不能調整大小。
- Vector 佔用更多的記憶體。
- Array 是記憶體高效的資料結構。
- Vector 在訪問元素時需要更多的時間。
- Array 以恆定時間訪問元素,而與它們的位置無關,因為這些元素排列在連續的記憶體分配中。
Vector 和陣列可以用以下語法宣告 -
Vector declaration:vector<datatype>array name; Array declaration:type array_name[array_size]; Vector initialization:vector<datatype>array name={values}; Array initialization:datatype arrayname[arraysize] = {values};
std::vector
示例程式碼
#include <iostream> #include <vector> using namespace std; int main() { vector<vector<int>>v{ { 4, 5, 3 }, { 2, 7, 6 }, { 3, 2, 1 ,10 } }; cout<<"the 2D vector is:"<<endl; for (int i = 0; i < v.size(); i++) { for (int j = 0; j < v[i].size(); j++) cout << v[i][j] << " "; cout << endl; } return 0; }
輸出
the 2D vector is: 4 5 3 2 7 6 3 2 1 10
std:: array
示例程式碼
#include<iostream> #include<array> using namespace std; int main() { array<int,4>a = {10, 20, 30, 40}; cout << "The size of array is : "; //size of the array using size() cout << a.size() << endl; //maximum no of elements of the array cout << "Maximum number of 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; // Filling array with 1 a.fill(1); // Displaying array after filling cout << "Array after filling operation is : "; for ( int i=0; i<4; i++) cout << a[i] << " "; return 0; }
輸出
The size of array is : 4 Maximum number of elements array can hold is : 4 The array elements are (using at()) : 10 20 30 40 Array after filling operation is : 1 1 1 1
廣告