Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
155 views
in Technique[技术] by (71.8m points)

c++ - What's wrong with cplusplus.com?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Edit: Documentation for std::remove has been fixed since this answer was written. Same thing applies to list::remove.

Let me give you an example to show you how cpluscplus.com can get it wrong.

Consider std::remove function from <algorithm>.

The fact is thatstd::remove doesn't remove the item from the container. Its because std::remove works with a pair of iterators only and does not know anything about the container which actually contains the items. In fact, it's not possible for std::remove to know the underlying container, because there is no way it can go from a pair of iterators to discover about the container to which the iterators belong. So std::remove doesn't really remove the items, simply because it cannot. The only way to actually remove an item from a container is to invoke a member function on that container.

So if you want to remove the items, then use Erase-Remove Idiom:

 v.erase(std::remove(v.begin(), v.end(), 10), v.end()); 

But cplusplus.com gives incorrect information about std::remove. It says

Notice that this function does not alter the elements past the new end, which keep their old values and are still accessible.

which isn't correct. The iterator in the range [new_end, old_end) is still dereferenceable, but that does NOT mean that they keep the old values and are still accessible. They are unspecified.


Similarly, cplusplus.com gives incorrect information about list::remove as well. It says,

Notice that a global algorithm function, remove, exists with a similar behavior but operating between two iterators.

which is completely wrong. The global remove namely std::remove is not similar to list::remove, as we saw that the former does NOT really remove the items from the container because it cannot, whereas the latter (the member function) really does remove the items because it can.

This answer is copied from my another answer in the following topic, with little modification:

Note: Since I came across this recently when I was replying in the above topic, I remember it. There are many errors which I've come across over the last two years, which I don't remember. I might add few more later, if I come across again.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...