Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between erase and remove

Tags:

c++

stl

I am bit confused about the difference between the usage of std::remove algorithm. Specifically I am not able to understand what is being removed when I use this algorithm. I wrote a small test code like this:

std::vector<int> a; a.push_back(1); a.push_back(2);  std::remove(a.begin(), a.end(), 1);   int s = a.size();  std::vector<int>::iterator iter = a.begin(); std::vector<int>::iterator endIter = a.end();  std::cout<<"Using iter...\n"; for(; iter != endIter; ++iter) {     std::cout<<*iter<<"\n"; }  std::cout<<"Using size...\n"; for(int i = 0; i < a.size(); ++i) {     std::cout<<a[i]<<"\n"; } 

The output was 2,2 in both the cases.

However, if I use erase with the remove something like this:

a.erase(std::remove(a.begin(), a.end(), 1), a.end()); 

I get the output as 2.

So my questions are:

(1). Is there any use of std::remove other than using it with erase function.

(2). Even after doing std::remove, why a.size() returns 2 and not 1?

I read the item in Scott Meyer's Effective STL book about the erase-remove idiom. But am still having this confusion.

like image 878
Naveen Avatar asked Apr 28 '09 18:04

Naveen


People also ask

What is the difference between to erase and to delete?

They sound synonymous but deleting and erasing a file are two different things. When you delete a file, you just reallocate it on the system making it harder to find, i.e., the files remain present in your system but are no more accessible. When you erase a file, it is gone forever.

Does erase mean delete?

When you erase something, you eliminate or delete it, often by physically wiping it out. It's easy to erase chalk from a blackboard, but not so easy to erase graffiti from the side of a building.

What is the difference between removing an app and deleting an app?

Then, hit "Remove." Next, choose between "Delete App" and "Remove from Home Screen." Deleting an app will erase all its data. Removing an app from the home screen (rather than deleting it) will send it to your app library.


1 Answers

remove() doesn't actually delete elements from the container -- it only shunts non-deleted elements forwards on top of deleted elements. The key is to realise that remove() is designed to work on not just a container but on any arbitrary forward iterator pair: that means it can't actually delete the elements, because an arbitrary iterator pair doesn't necessarily have the ability to delete elements.

For example, pointers to the beginning and end of a regular C array are forward iterators and as such can be used with remove():

int foo[100];  ...  remove(foo, foo + 100, 42);    // Remove all elements equal to 42 

Here it's obvious that remove() cannot resize the array!

like image 177
j_random_hacker Avatar answered Sep 24 '22 07:09

j_random_hacker