Reputation: 31
I read that std::sort
only accepts random access iterators. So, I expected to find code in the sort
function that ensures only random access iterators are accepted, but I couldn't find any.
Why is it that std::sort
can only take random access iterators? Did I miss something?
I'm using MSVC STL with C++17.
Upvotes: 2
Views: 111
Reputation: 123114
That the iterator is a random access iterator is a requirement of std::sort
. If the iterator passed to std::sort
does not meet the requirements of the named requirement LegacyRandomAccessIterator then std::sort
might work correctly or not. In any case the program is ill-formed. std::sort
assumes that the iterator is a random access iterator, it does not have to explicitly check that it is one. std::sort
uses operations that a RandomAccessIterator supports. If the iterator is not a RandomAccessIterator those operations might fail.
std::sort
can check the requirements listed, but it does not have to. It's up to you to make sure the iterator meets them.
It's like you apply for a job where they require you to be able to jump 15m high. In the interview they will do the usual chat, but they will not check that you can jump that high. They assume you can, because they clearly stated it as requirement for the job. On day one you have to jump and you fail. End of story ;).
Upvotes: 4