简体   繁体   中英

Why does std::reverse require bidirectional iterators?

Why does std::reverse(c.begin(), c.end()) require that the underlying container c provides bidirectional iterator ?

De-facto this would mean (multi-) map , (multi-) set , but those can not reversed, of course, because they are ordered. The only other bi-dir container is list but that one has its own member function .reverse() .

This means that one can apply std::reverse on array , vector and deque which are random-access .

So, why not be "honest" and say: random-access is required, or use the member function?

You don't even need to go user-defined iterators, you provide an answer in your own question.

The only other bi-dir container is list but that one has its own member function .reverse() .

That member function, however, reverses the whole list. std::reverse allows only part of the list to be reversed, by passing other iterators than list.begin() and list.end() .

Doing this would be unnecessarily restrictive for user-defined iterators or cointainers using bidireactional iterators. And since random access is not necessary, it shouldn't be required.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM