What are the advantages of std::distance over subtracting iterators in C++?
Hello colleagues! I recently started learning C++ and encountered an interesting point when working with iterators. Suppose I have std::vector v = {10, 20, 30, 40, 50}; and I want to find the distance between two iterators, for example, from the beginning to the middle.
I know that for random access iterators (like those of vector), you can simply subtract one iterator from another: auto mid = v.begin() + 2; ptrdiff_t dist = mid - v.begin(); // dist = 2. This works and seems very simple.
But in other developers' code, I often see the use of std::distance: auto dist = std::distance(v.begin(), mid);. And I don't understand why use a function if you can just subtract? After all, subtraction is shorter and probably faster?
I understand that std::distance is a template function from the header. But
No answers yet.
Log in to leave an answer
Blogs
How to Write a REST API in C++ in 30 Minutes: A Quick Start
Refactoring Legacy Code in Kotlin: Strategy and Examples