Erasing elements from a vector

后端 未结 5 704
萌比男神i
萌比男神i 2020-11-21 12:57

I want to clear a element from a vector using the erase method. But the problem here is that the element is not guaranteed to occur only once in the vector. It may be presen

5条回答
  •  心在旅途
    2020-11-21 14:03

    1. You can iterate using the index access,

    2. To avoid O(n^2) complexity you can use two indices, i - current testing index, j - index to store next item and at the end of the cycle new size of the vector.

    code:

    void erase(std::vector& v, int num)
    {
      size_t j = 0;
      for (size_t i = 0; i < v.size(); ++i) {
        if (v[i] != num) v[j++] = v[i];
      }
      // trim vector to new size
      v.resize(j);
    }
    

    In such case you have no invalidating of iterators, complexity is O(n), and code is very concise and you don't need to write some helper classes, although in some case using helper classes can benefit in more flexible code.

    This code does not use erase method, but solves your task.

    Using pure stl you can do this in the following way (this is similar to the Motti's answer):

    #include 
    
    void erase(std::vector& v, int num) {
        vector::iterator it = remove(v.begin(), v.end(), num);
        v.erase(it, v.end());
    }
    

提交回复
热议问题