c++对vector容器进行边遍历边删除的安全例子
时间: 2023-12-23 10:04:44 浏览: 33
在C++中,对于一个容器进行边遍历边删除是不安全的操作。因为删除元素会改变容器的大小和元素的位置,可能会导致程序出现未定义的行为。
为了安全地删除vector容器中的元素,我们可以使用STL提供的erase-remove惯用法。这种惯用法将删除操作分成两步:首先使用remove函数将要删除的元素移到容器末尾,然后再使用erase函数删除末尾的元素。
下面是一个安全地删除vector容器中元素的例子:
```c++
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
vector<int> vec = {1, 2, 3, 4, 5};
// 删除所有偶数元素
vec.erase(remove_if(vec.begin(), vec.end(), [](int i){return i % 2 == 0;}), vec.end());
// 输出删除后的元素
for (auto i : vec)
{
cout << i << " ";
}
cout << endl;
return 0;
}
```
在上面的代码中,我们使用remove_if函数来移动要删除的元素,然后使用erase函数删除末尾的元素。这样做可以确保我们安全地删除vector容器中的元素。
相关问题
c++对vector容器进行边遍历边删除的安全迭代器例子
在C++中,对于vector容器的遍历和删除操作,需要使用安全迭代器来确保程序的正确性。安全迭代器的使用可以避免在遍历过程中对容器的修改操作引起的未定义行为。
以下是一个对vector容器进行边遍历边删除的安全迭代器例子,代码如下:
```cpp
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> vec = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
for (auto it = vec.begin(); it != vec.end(); ) {
if (*it % 2 == 0) {
it = vec.erase(it); // 安全删除
} else {
cout << *it << " "; // 输出奇数元素
++it;
}
}
return 0;
}
```
在上面的例子中,我们使用了for循环来遍历vector容器,使用auto类型推导得到迭代器类型,然后在循环体内部,判断当前元素是否为偶数,如果是偶数,则使用安全删除函数erase()将其从容器中删除,否则输出奇数元素并将迭代器指向下一个元素。
需要注意的是,安全删除函数erase()返回的是下一个元素的迭代器,因此在执行erase()操作之后,需要将迭代器更新为erase()的返回值,以便继续遍历容器中的元素。
c++ 二维容器如何遍历
在C++中,遍历二维容器可以使用嵌套的循环或者使用迭代器。以下是两种常见的遍历二维容器的方法:
1. 使用嵌套循环遍历:
```cpp
std::vector<std::vector<int>> matrix; // 假设为一个二维容器
// 使用嵌套循环遍历二维容器
for (size_t i = 0; i < matrix.size(); ++i) {
for (size_t j = 0; j < matrix[i].size(); ++j) {
// 访问二维容器中的元素
int element = matrix[i][j];
// 进行相应的操作
}
}
```
在上述例子中,外层循环控制行数,内层循环控制列数,通过`matrix[i][j]`来访问二维容器中的元素。
2. 使用迭代器遍历:
```cpp
std::vector<std::vector<int>> matrix; // 假设为一个二维容器
// 使用迭代器遍历二维容器
for (auto it1 = matrix.begin(); it1 != matrix.end(); ++it1) {
for (auto it2 = it1->begin(); it2 != it1->end(); ++it2) {
// 访问二维容器中的元素
int element = *it2;
// 进行相应的操作
}
}
```
在上述例子中,外层迭代器`it1`遍历行,内层迭代器`it2`遍历列,通过`*it2`来访问二维容器中的元素。
无论是使用嵌套循环还是迭代器,你都可以在遍历过程中对二维容器的元素进行相应的操作。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)