c++ remove_if能刪除所有條件項(xiàng)嗎

c++
小樊
86
2024-07-26 13:01:07

是的,可以通過(guò)使用remove_if函數(shù)來(lái)刪除所有滿足條件的元素。remove_if函數(shù)接受一個(gè)條件函數(shù)作為參數(shù),該函數(shù)返回true表示應(yīng)該刪除該元素。使用remove_if函數(shù)后,可以結(jié)合erase函數(shù)來(lái)刪除滿足條件的元素。例如:

#include <iostream>
#include <vector>
#include <algorithm>

bool isEven(int num) {
    return num % 2 == 0;
}

int main() {
    std::vector<int> nums = {1, 2, 3, 4, 5, 6, 7, 8, 9};

    nums.erase(std::remove_if(nums.begin(), nums.end(), isEven), nums.end());

    for (int num : nums) {
        std::cout << num << " ";
    }

    return 0;
}

在上面的示例中,isEven函數(shù)用于判斷一個(gè)數(shù)是否為偶數(shù),然后使用remove_if和erase函數(shù)來(lái)刪除所有偶數(shù)。

0