I have encountered strange behavior of iterators on empty <vector>
. In my code, even though std::cend(children) - 1 - std::cbegin(children)
is clearly negative ( 0 -1 -0
), their comparison std::cbegin(children) < (std::cend(children) - 1)
result is true
( 0 < (0-1)
). Is this compiler bug or language specification or undefined behavior ?
#include <iostream>
#include <vector>
int main() {
std::vector<int> children{};
auto pointer_to_child_first = std::cbegin(children);
auto pointer_to_child_last = std::cend(children) - 1;
auto pointer_to_child_current = pointer_to_child_first;
for (; pointer_to_child_current < pointer_to_child_last; pointer_to_child_current += 1) {
std::cout << ">if less code\n";
}
if (pointer_to_child_current == pointer_to_child_last) {
std::cout << ">if equals code\n";
}
}
Output:
>if less code
>if less code
>if less code
>if less code
>if less code
^C
If I change std::cbegin
and std::cend
to std::crbegin
and std::crend
or to std::crend
and std::crbegin
, than I got all as intended.
Compiler version:
>clang-cl.exe -v
clang version 8.0.0 (tags/RELEASE_800/final)
Target: x86_64-pc-windows-msvc
What happens when you're looking at a leaf node (a node with no children)? Specifically, what will this line do:
auto&& pointer_to_child_last = std::cend(children) - 1;
Since std::cbegin(children) == std::cend(children)
, this is illegal!
To remedy this, if the node is a leaf, just return your accumulator string after you've added the node number:
if(children.size() == 0) { return accumulator.str(); }
See it in action: http://ideone.com/1oh9yr
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.