-2

I would like to modify a member function of the vector class. Is this possible? For example I would like to be able to delete with respect to value, and not the integer of the vector.

Matias
  • 3
  • 2

1 Answers1

2

I think this does what you are looking for. This example removes all the occurrences of the number 6 from a vector using std::remove. xs.erase is to make sure the vector removes the elements and shrinks the vector to the new size.

I generally avoid modifying the STL containers as the people who implemented them are likely far smarter than me when it comes to this kind of thing. I recommend you learn the standard library algorithms, there generally is one suited to most kinds of general container operations.

#include <iostream>
#include <algorithm>

int main(int argc, char** argv)
{
    std::vector<int> xs{1, 3, 6, 2, 6, 5};

    std::cout << "xs size: " << xs.size() << std::endl; // xs.size() == 6   

    auto value_to_remove = 6;

    xs.erase(std::remove(xs.begin(), xs.end(), value_to_remove), xs.end());

    for (const auto& x : xs)
        std::cout << x << ", ";
    std::cout << std::endl; // 1, 3, 2, 5, 

    std::cout << "xs size: " << xs.size() << std::endl; // xs.size() == 4 

    return 0;
}

In this case, as with most other STL algorithms value_to_remove can be replaced with a (unary) lambda predicate opening up a whole world of exotic value finding.

You could wrap the above in a function as follows:

template <typename T>
void erase_by_value(std::vector<T>& xs, const T& value_to_remove)
{
    xs.erase(std::remove(xs.begin(), xs.end(), value_to_remove), xs.end());

}
bjpelcdev
  • 303
  • 3
  • 9