我尝试在删除元素后减少数组的长度 我有尝试数组:
int* arr = new int[5];
for (int i = 0; i < 5; i++) {
arr[i] = i;
}
和功能:
void del1(int* arr, int n) {
int pos = 0;
for (int i = 0; i < n; i++) {
if (arr[i] == 3) {
pos = i;
}
}
for (int i = pos; i < n - 1; i++) {
arr[i] = arr[i + 1];
}
arr[n - 1] = 0;
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
}
有没有办法减少发送给函数的数组的长度?
你要找的东西在 C++ 中是这样表达的: (在线演示:https://onlinegdb.com/OiDJg4849)
#include <algorithm>
#include <iostream>
#include <vector>
int main()
{
std::vector<int> values{ 1,2,3,4,5 };
// remove/erase idiom
// https://en.cppreference.com/w/cpp/algorithm/remove
// the last argument is a lambda expression
// https://en.cppreference.com/w/cpp/language/lambda
auto it = std::remove(values.begin(), values.end(), 3);
values.erase(it, values.end());
//https://en.cppreference.com/w/cpp/language/range-for
for (const auto& value : values)
{
std::cout << value << "\n";
}
return 0;
}