Reputation: 182772
In the book 'C++ In A Nutshell', there is the following example code
std::vector<int> data
...
std::erase(std::remove(data.begin(), data.end(), 42),
data.end());
I thought that 'erase' was a member function, so shouldn't that be 'data.erase' rather than 'std::erase'? Is there some way the c++ compiler can tell what member you wanted to call a member function on, or did the book omit any documentation of an erase template function, or is the example wrong?
Upvotes: 2
Views: 2032
Reputation: 984
There is an algorithm called std::remove. And calling erase on the data structure. remove moves all the elements to be erased to the end of the iterator range and returns the first element to be removed. Returns end() if the element could not be found.
So then you call erase on range starting with the return value of std::remove and the end of the data structure.
See: http://www.sgi.com/tech/stl/remove.html
Note that remove won't work with ordered datastructures, as the elements can't be rearranged.
remove is linear, and so would be removing a vector from up to the end. As it wouldn't need to bubble up the elements after the elements to be removed.
std::vector<int> data
...
data.erase(std::remove(data.begin(), data.end(), 42), data.end())
compared to something like this which is O(N**2)
std::vector<int> data
...
for ( i = data.begin(), i != data.end(); ++i ) {
if ( *i == 42 ) data.erase( i ) ;
}
Upvotes: 0
Reputation: 16096
You observation is correct. 'Erase' should be a member function. Only a member function on a container can change the memory size of that container.
Upvotes: 3
Reputation: 26975
There is no std::erase
. std::map::erase
, std::list::erase
exists. But no std::erase
exists.
Look this question about phantom std::erase.
Upvotes: 7
Reputation: 490088
Yes, erase is a member function, so it should be data.erase()
instead of std::erase()
.
Upvotes: 3
Reputation: 101565
erase
is a member function. The sample provided is incorrect.
Upvotes: 13