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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP