Using vector for dynamic array processing

In C++, vector is a container class in the Standard Template Library (STL), which provides the function of dynamic arrays. It stores elements contiguously in memory and provides efficient operations for accessing, inserting, and deleting elements.

The header file of vector is<vector>, which needs to be included when using it.

The following introduces some common operations and features of vector:

1. Definition and initialization:

vector<int> vec; // 定义一个空的int类型的vector
vector<int> vec(5); // 定义一个包含5个元素的int类型的vector,每个元素都被默认初始化为0
vector<int> vec = {
    
    1, 2, 3, 4, 5}; // 使用初始化列表定义vector,并赋予初值

2. Access elements:

int value = vec[0]; // 通过下标访问元素,注意不做范围检查
int value = vec.at(0); // 通过at()函数访问元素,进行范围检查,超出范围会抛出异常
int value = vec.front(); // 获取第一个元素
int value = vec.back(); // 获取最后一个元素

3. Inserting and deleting elements:

vec.push_back(10); // 在尾部插入一个元素
vec.pop_back(); // 移除尾部的元素
vec.insert(vec.begin() + 2, 20); // 在指定位置插入一个元素
vec.erase(vec.begin() + 1); // 移除指定位置的元素

4. Capacity related:

bool isEmpty = vec.empty(); // 判断vector是否为空
int size = vec.size(); // 返回vector中元素的个数
int capacity = vec.capacity(); // 返回vector当前可容纳的元素个数
vec.reserve(100); // 将vector的容量设置为至少能容纳100个元素,可以避免不必要的内存重新分配
vec.resize(10); // 将vector的大小调整为10,多余的元素会被删除或者使用默认值填充

5. Traverse:

for (int i = 0; i < vec.size(); ++i) {
    
    
    cout << vec[i] << " ";
}
cout << endl;

for (auto it = vec.begin(); it != vec.end(); ++it) {
    
    
    cout << *it << " ";
}
cout << endl;

for (int value : vec) {
    
    
    cout << value << " ";
}
cout << endl;

Vector provides flexible dynamic array functions that can easily add, delete and access elements. The time complexity of initialization, insertion and deletion operations is O(1), and the time complexity of random access to elements through subscripts is also O(1). Therefore, using vector is an efficient and convenient option in most cases.

Guess you like

Origin blog.csdn.net/weixin_75094128/article/details/131537430