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.
Asked
Active
Viewed 363 times
-2
-
1Why do you want to do this? – The Forest And The Trees Apr 16 '15 at 10:29
-
Hi @Matias welcome to stack overflow this question was asked before. just search using google or the search bar of the site. – Nahum Apr 16 '15 at 10:29
-
Which one, to do what, and why? – Bathsheba Apr 16 '15 at 10:31
-
A better approach would be to look at the algorithms library. See http://www.cplusplus.com/reference/algorithm/. There may well be a function there for you already. – Bathsheba Apr 16 '15 at 10:33
-
1What's wrong with using [`remove/remove_if`](http://en.cppreference.com/w/cpp/algorithm/remove) from the `
` header? – AliciaBytes Apr 16 '15 at 10:36 -
Adding/removing/changing a member function is completely the wrong approach here, since the function you want is well within what's possible on top of vector's existing public API. – Puppy Apr 16 '15 at 10:40
1 Answers
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