c++syntax

Could the vector begin() be deduced?


I wonder why C++ is designed to insist on the iterator syntax? Why is it not possible to ommit the begin() iterator in some contexts? For example:

std::copy(v.begin() + 1, v.begin() + 3, w.begin() + 6);

would look so much readable like this:

std::copy(v + 1, v + 3, w + 6);

This is not a question of why the latter is not correct. The question is about what could have motivated the accepted syntax? In fact, since:

std::copy(v.begin() + 1, u.begin() + 3, w.begin() + 6);

is probably an error, I wonder why not define the copy to accept the following instead:

std::copy(v + 1, 2, w + 6);

where you copy 2 elements.

I am looking for some insightful reason so that I can have some love for the complicated syntax.


Solution

  • This is not an unreasonable question. This time, we do have to look at the real STL - the Standard Template Library by Stepanov and Lee, from 1997. This library was then incorporated into to the Standard Library of ISO C++98.

    The STL generalized the pointer concept into iterators. It is absolutely intentional that std::copy(ptr+1, ptr+7, otherPtr+6) works. In fact, std::copy(array+1, array+7, otherArray+6) also works. That is exactly the syntax from the question.

    However, even back in 1997, it was understood that the array-to-pointer decay was an unfortunate legacy from C. It's caused quite a number of problems historically, for instance in function arguments. That is why the STL containers do not have that conversion to their iterators.