std::vector和vector
时间: 2024-09-07 15:03:22 浏览: 82
`std::vector`是C++标准库中的一个动态数组容器,它属于STL(Standard Template Library,标准模板库)的一部分。`std::vector`是一个动态大小的数组,可以在运行时自动调整容量,提供元素的增删操作,以及方便的随机访问功能。
与普通的数组相比,`std::vector`的主要优点包括:
1. **动态扩容**:当向容器添加元素超出当前容量时,会自动分配新的内存空间,并将原有数据复制过去,避免了频繁地手动扩容或缩容。
2. **范围迭代**:可以使用`begin()`和`end()`函数获取元素的起始和结束迭代器,支持简单的for循环遍历。
3. **容量管理**:`size()`用于获取元素个数,`reserve()`可以预分配内存空间,提高效率。
4. **安全机制**:如果试图访问越界的位置,不会导致程序崩溃,而是抛出异常。
创建`std::vector`的基本语法如下:
```cpp
std::vector<T> vec; // 创建空的vector
std::vector<T> vec(size); // 初始化指定长度的vector
std::vector<T> vec(array, size); // 使用数组初始化
```
相关问题
std::vector如何追加std::vector
可以使用`insert()`函数或者`resize()`函数来追加`std::vector`。其中,`insert()`函数可以在任意位置插入元素,而`resize()`函数只能在末尾插入元素。下面分别举例说明:
引用中的构造函数部分介绍了如何构造一个空的`vector`和一个包含指定数量的元素的`vector`。可以使用这些构造函数创建一个空的`vector`或者包含若干个指定值的`vector`。例如:
```c++
std::vector<std::vector<int>> vec1; // 创建一个空的vector
std::vector<std::vector<int>> vec2(3, std::vector<int>(4, 1)); // 创建一个由3个vector构成,每个vector包含4个值为1的int值
```
1.使用`insert()`函数追加`std::vector`[^1]
```c++
std::vector<std::vector<int>> vec{{1,2,3},{4,5,6}};
std::vector<int> new_vec{7,8,9};
vec.insert(vec.end(), new_vec.begin(), new_vec.end());
```
上述代码首先创建了一个包含两个vector的vector`vec`,然后创建一个新的vector`new_vec`,最后将`new_vec`追加到`vec`的末尾,实现了向`std::vector`中追加`std::vector`的操作。
2.使用`resize()`函数追加`std::vector`
```c++
std::vector<std::vector<int>> vec{{1,2,3},{4,5,6}};
std::vector<int> new_vec{7,8,9};
vec.resize(vec.size()+1, new_vec);
```
上述代码首先创建了一个包含两个vector的vector`vec`,然后创建一个新的vector`new_vec`,最后将`new_vec`追加到`vec`的末尾,实现了向`std::vector`中追加`std::vector`的操作。
std::arrayhe vector
std::array和vector是C++中用于存储多个元素的容器类。它们有一些共同点,但也有一些区别。
1. 相似之处:
- 都可以用来存储多个元素。
- 都提供了成员函数来访问和修改容器中的元素。
- 都支持动态大小调整。
- 都支持迭代器,可以通过迭代器遍历容器中的元素。
2. 不同之处:
- std::array是固定大小的数组,其大小在编译时确定,并且不能动态调整。而vector是动态数组,可以在运行时动态增长或缩小。
- std::array的大小是固定的,因此它的内存是在栈上分配的。而vector的大小可以在运行时改变,因此它的内存是在堆上分配的。
- std::array的大小是在编译时确定的,因此它的元素数量必须是常量表达式。而vector的大小可以是变量,可以根据需要进行调整。
- std::array没有提供插入或删除元素的成员函数,因为其大小是固定的。而vector提供了插入、删除等操作,因为它支持动态大小调整。
总之,如果你需要一个固定大小且不需要动态调整的数组,可以使用std::array。如果你需要一个可以动态调整大小的数组,并且需要在运行时插入、删除元素,可以使用vector。
阅读全文
相关推荐















