#include <iostream>
#include <vector>
using namespace std;
// 函数用于删除数组中的某个元素
void removeElement(vector<int>& nums, int val) {
// 使用 erase-remove idiom 删除指定元素
nums.erase(remove(nums.begin(), nums.end(), val), nums.end());
}
int main() {
vector<int> arr = {1, 2, 3, 4, 5, 3, 6};
int val = 3;
cout << "原始数组: ";
for (int num : arr) {
cout << num << " ";
}
cout << endl;
removeElement(arr, val);
cout << "删除元素 " << val << " 后的数组: ";
for (int num : arr) {
cout << num << " ";
}
cout << endl;
return 0;
}
removeElement
函数:该函数接收一个 vector<int>
类型的引用和一个要删除的整数值。它使用了 C++ 标准库中的 std::remove
和 std::vector::erase
方法来移除所有等于给定值的元素。
std::remove
将所有不等于给定值的元素移动到向量的前面,并返回指向新末尾位置的迭代器。std::vector::erase
则根据这个迭代器删除从新末尾位置到原末尾位置的所有元素。主函数 main
:创建了一个包含多个整数的 vector
,并调用 removeElement
函数删除指定的元素。最后输出删除前后的数组内容以便对比。
输出结果:程序会先打印原始数组,然后删除指定元素后再次打印修改后的数组。
上一篇:c++ 内部类
下一篇:c++条件运算符
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站