c++编写一个函数replaceNeg,将容器内前n个元素中负值替换为0
时间: 2024-02-25 07:57:57 浏览: 22
好的,以下是代码实现:
```c++
#include <iostream>
#include <vector>
using namespace std;
void replaceNeg(vector<int>& nums, int n)
{
for (int i = 0; i < n; i++) {
if (nums[i] < 0) {
nums[i] = 0;
}
}
}
int main()
{
vector<int> nums = {-1, 2, -3, 4, -5, 6, -7, 8, -9, 10};
int n = 5;
cout << "替换前:";
for (int i = 0; i < nums.size(); i++) {
cout << nums[i] << " ";
}
cout << endl;
replaceNeg(nums, n);
cout << "替换后:";
for (int i = 0; i < nums.size(); i++) {
cout << nums[i] << " ";
}
cout << endl;
return 0;
}
```
这里使用了引用传递vector容器,以便在函数内部修改容器。函数replaceNeg接受两个参数:一个是vector<int>类型的容器,另一个是需要替换负值的前n个元素。在函数内部,使用for循环遍历容器中的前n个元素,如果是负值,则将其替换为0。最后在main函数中测试replaceNeg函数,输出替换前和替换后的容器中的元素即可。