代码之家  ›  专栏  ›  技术社区  ›  Dennis M.

如何在C++中删除小于X的数组中的整数?

  •  2
  • Dennis M.  · 技术社区  · 7 年前

    我在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 . 我试图绕过这个问题,即我不知道新阵列应该有多长。

    有没有更好的方法来解决这个问题?

    2 回复  |  直到 7 年前
        1
  •  5
  •   null    7 年前

    是,使用 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 语法,因为它不会自动取消分配,不像 标准::矢量 .

    此外,虽然这与问题无关,但C++提供了一个函数,它可以完成您想要调用的功能 std::copy_if .

        2
  •  0
  •   Mário Feroldi    7 年前

    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::删除 跑步,你可以 {1, 314, 42, 42} end 超过最后一个不匹配元素的点(本例中为前42个)。

    还可以使用将不匹配的元素复制到另一个数组 std::remove_copy std::copy_if ,但为了做到这一点,您必须分配另一个元素数组。此时,最好使用动态增长的数组,如 std::vector . 在这种情况下,使用 std::vector::erase 喜欢 here in the answers 具有 std::删除 .