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?
CodePudding user response:
The order in which the arguments in a function call are evaluated is unspecified.
--first
may execute first or first
may execute first. If the former is the case, the decrement has undefined behavior, because decrementing a .begin()
iterator is not allowed. Since one of the allowed execution orders has undefined behavior, your whole program has undefined behavior.
Using first--
instead doesn't change anything about this.
CodePudding user response:
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));
CodePudding user response:
std::distance(--first, first)
This is undefined behavior. You are modifying the same variable twice. this is essentially the same as i i
.