我在PHP中找到了同样的问题,我尝试在C ++中做同样的事情。
我试过以下:
// returns new array with numbers lower then "number", len is set to
// new length.
int * filter(int array[], int &len, int number) {
int cnt = 0;
for (int i = 0; i < len; i++) {
if (array[i] < number) {
cnt++;
}
}
int *ret = new int[cnt];
cnt = 0;
for (int i = 0; i < len; i++) {
if (array[i] < number) {
ret[cnt] = array[i];
cnt++;
}
}
len = cnt;
return ret;
}
此函数将创建一个整数低于整数number
的新数组。我试图绕过我不知道新阵列应该有多长时间的问题。
有没有更好的方法来解决这个问题?
答案 0 :(得分:5)
是的,请使用std::vector
类型。每次向其推送值时,它都会自动为您处理分配(使用push_back
方法)。
#include <iostream>
#include <vector>
int main() {
std::vector<int> a;
a.push_back(1);
a.push_back(2);
for (int value : a) {
std::cout << value << '\n';
}
}
与new
不同,避免std::vector
语法也是一个好主意,因为它不会自动解除分配。
此外,虽然这与问题无关,但C ++提供的功能可以执行您想要的std::copy_if
。
答案 1 :(得分:0)
std::remove
是您正在寻找的算法。
#include <iterator>
#include <algorithm>
int main()
{
int array[4] = {1, 42, 314, 42};
// If you only know `array` as a pointer, and `len`, then
// `std::begin(array)` becomes `array`, and
// `std::end(array)` becomes `array + len`.
auto end = std::remove(std::begin(array), std::end(array), 42);
// Now `end` points to the "new end" of the array.
// And `std::distance(std::begin(array), end)` is the "new length".
}
它将所有匹配的元素(在示例中为42)移动到数组的末尾。在array
运行后检查std::remove
时,您会获得{1, 314, 42, 42}
和end
点超过最后一个不匹配元素(在这种情况下为前42个)。
也可以使用std::remove_copy
或std::copy_if
将不匹配的元素复制到另一个数组,但为了做到这一点,您必须分配另一个数组元素。此时,您最好使用动态增长数组,例如std::vector
。在这种情况下,请std::vector::erase
使用here in the answers和std::remove
。