如何删除小于C 中x的数组中的整数

How to remove integers in array less than X in C++?

本文关键字:数组 整数 小于 何删除 删除      更新时间:2023-10-16

我发现了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。我试图绕过我不知道新数组应该多长时间的问题。

有什么更好的方法可以解决此问题?

是的,使用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';
    }
}

std::vector不同,避免new语法也是一个好主意。

另外,尽管这与问题无关,但C 提供了一个可以执行您想要的已称为std::copy_if的函数。

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个(移至数组末端。在std::remove运行后检查array时,您将获得{1, 314, 42, 42},并且end指向最后一个不匹配元素(在这种情况下为第一个42(。

也可以使用std::remove_copystd::copy_if将非匹配元素复制到另一个数组,但是为了做到这一点,您必须分配另一个元素数组。在这一点上,最好使用动态增长阵列(例如std::vector(。在这种情况下,使用std::remove的答案中的std::vector::erase