删除vector容器内小于3的C++代码
以下是删除vector容器内小于3的C++代码:
#include <iostream>
#include <vector>
int main() {
std::vector<int> nums = {1, 2, 3, 4, 5};
// 删除小于3的元素
for (auto it = nums.begin(); it != nums.end(); ) {
if (*it < 3) {
it = nums.erase(it);
} else {
++it;
}
}
// 输出删除后的vector容器
for (int num : nums) {
std::cout << num << " ";
}
std::cout << std::endl;
return 0;
}
运行以上代码,输出结果为:
3 4 5
注意,我们使用nums.erase(it)来删除元素,并且在删除元素后不需要自增迭代器,因为erase函数会返回下一个有效的迭代器
原文地址: https://www.cveoy.top/t/topic/hHL6 著作权归作者所有。请勿转载和采集!