'How come std::distance() doesn't work for rvalues?
For example:
std::list <int> list1 = {1, 2, 3, 4, 5};
auto first = list1.begin();
std::cout << std::distance(--first, ++first);
The output is 0. Strange enough, if we change --first to first--, the output becomes 5 (although here it should be 0, as it returns first). What am I missing?
Solution 1:[1]
Neither --first nor ++first is an rvalue. They are lvalues.
You are also not allowed to decrement the iterator returned by begin().
To get the distance between two rvalues, you could use std::prev and std::next:
auto second = std::next(list1.begin()); // to make std::prev(second) ok
std::cout << std::distance(std::prev(second), std::next(second));
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ted Lyngmo |
