简体   繁体   English

从C ++中的向量中删除偶数

[英]Remove even numbers from a vector in c++

can somebody help me with this function: suppose that I need to remove all even numbers from a vector using reference: can I do that?有人可以帮我实现这个功能:假设我需要使用引用从向量中删除所有偶数:我可以这样做吗? Is the push_back correct or should I use something else? push_back 正确还是我应该使用其他东西?

void evenRemoe(vector<int>& arr) {
    for(int i = 0; i < arr.size(); i++) {
        if(arr[i] % 2 != 0) {
            push_back(arr[i]);
        }  
    }
}

Using push_back adds elements so that's not going to work.使用push_back添加元素,所以这是行不通的。

You can usestd::erase_if with a functor, like a lambda or other function acting as a unary predicate, to decide what elements that should be removed.您可以将std::erase_if与仿函数(如 lambda 或其他充当一元谓词的函数)一起使用,以决定应删除哪些元素。

void evenRemoe(std::vector<int>& arr) {
    std::erase_if(arr, [](int i) { return i % 2 == 0; });
}

Prior to C++20 you could implement the erase–remove idiom在 C++20 之前,您可以实现擦除-删除习惯用法

#include <algorithm>
void evenRemoe(std::vector<int>& arr) {
    arr.erase(std::remove_if(arr.begin(), arr.end(),
                             [](int i) { return i % 2 == 0; }),
              arr.end());
}

No, push_back() is not the correct thing to use.不, push_back()不是正确的使用方法。 That is meant for adding values, not removing them.这是为了增加价值,而不是删除价值。

Also, your code is actually looking for odd values, not even values.此外,您的代码实际上是在寻找奇数,而不是偶数

You can use std::vector::erase() to remove individual values, eg:您可以使用std::vector::erase()删除单个值,例如:

void evenRemoe(vector<int>& arr){
    for(size_t i = 0; i < arr.size();){
        if (arr[i] % 2 == 0){
            arr.erase(arr.begin()+i);
        }else{
            ++i;
        }
    }
}

Alternatively, consider using the Erase-Remove idiom via std::remove_if() and std::vector::erase() , eg:或者,考虑通过std::remove_if()std::vector::erase()使用Erase-Remove 习语,例如:

#include <algorithm>

void evenRemoe(vector<int>& arr){
    arr.erase(
        std::remove_if(arr.begin(), arr.end(),
            [](int value){ return (value % 2) == 0; }
        ),
        arr.end()
    );
}

Or, in C++20, viastd::erase_if() , eg:或者,在 C++20 中,通过std::erase_if() ,例如:

void evenRemoe(vector<int>& arr){
    std::erase_if(arr,
        [](int value){ return (value % 2) == 0; }
    );
}

push_back is a method of std::vector for appending an element to the end of the vector, not removing . push_backstd::vector的一种方法,用于将元素附加到向量的末尾,而不是删除. What you need is one of the erase methods.您需要的是其中一种erase方法。

However, you should be careful while erasing elements of the vector you're iterating over.但是,在擦除正在迭代的向量的元素时应该小心。 Care must be taken to avoid incrementing the index when you remove the element.必须注意避免在删除元素时增加索引。

The better way to do this is to use std::remove_if algorithm instead of iterating the vector yourself.更好的方法是使用std::remove_if算法而不是自己迭代向量。

void evenRemove(vector<int>& arr) {
    auto it = std::remove_if(arr.begin(), arr.end(),
        [](int n) { return (n % 2) == 0; });
    arr.erase(it, arr.end());
}

Despite the name, std::remove_if doesn't actually remove any elements from the vector.尽管有名称,但std::remove_if实际上并没有从向量中删除任何元素。 Instead, it moves the elements that match the predicate (in our case - all even integers) to the end of the vector and returns an iterator pointing to the first of such elements.相反,它将与谓词匹配的元素(在我们的例子中 - 所有偶数整数)移动到向量的末尾并返回指向第一个此类元素的迭代器。 Therefore, to actually remove the elements you need to call erase with the iterators denoting the tail of the vector that contains the even integers.因此,要真正删除元素,您需要调用erase ,迭代器表示包含偶数的向量的尾部。

From C++20 onwards you can use std::erase_if(), Prior to c++20 erase-remove idiom used to be the solution of this problem.从 C++20 开始,您可以使用 std::erase_if(),在 c++20 之前,擦除-删除习语曾经是这个问题的解决方案。

v.erase(std::remove_if(v.begin(), v.end(), is_even), v.end());

Where is_even is a functor is_even 是一个函子

Remove multiple element from vector using iterator.使用迭代器从向量中删除多个元素。 Just take care that when we erase using iterator,it goes invalid.请注意,当我们使用迭代器擦除时,它会失效。

int main(){
        vector<int> vec={1,2,3,4,5,6,7,8,9};
        for(auto it=vec.begin();it!=vec.end();){
           if(*it%2==0)
               vec.erase(it);
           else
               it++;
        }
        for(auto i:vec){
            cout<<i<<" ";
        }
        return 0;
    }

output:1 3 5 7 9输出:1 3 5 7 9

2nd method第二种方法

int main(){
    vector<int> vec={1,2,3,4,5,6,7,8,9};
    vec.erase(remove_if(vec.begin(),vec.end(),[](int i){
        return i%2==0;
    }),vec.end());

    for(auto i:vec)
        cout<<i<<" ";
    
    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM