[英]C++ strange output with cout and reverse_iterator
I find a very strange output in C++ when I try to use vector's reverse_iterator to do a traverse. 当我尝试使用向量的reverse_iterator进行遍历时,我在C ++中发现一个非常奇怪的输出。 My code is simple and like this:
我的代码很简单,像这样:
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
vector<int>::reverse_iterator it = v.rbegin();
cout << *it++ << " " << *it++;
return 0;
}
The output is 2 3. I can't figure out what happened in it. 输出为23。我不知道发生了什么。 Can anyone help me out?
谁能帮我吗?
I don't know how long you've been doing C++, but again, Welcome to C++ :-) ... 我不知道您从事C ++已经有多长时间了,但是再次,欢迎使用C ++ :-) ...
You have just entered the world of Undefined Behaviors and sequence points 您刚刚进入了未定义行为和顺序点的世界
You should break your code down into: 您应该将代码分解为:
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
vector<int>::reverse_iterator it = v.rbegin();
cout << *it;
it++;
cout << " " << *it;
return 0;
}
It works now... :-) 现在可以使用... :-)
Let me explain give you a brief overview of what is happening in your original code... 让我解释一下,以简要概述原始代码中发生的事情...
This line 这条线
cout << *it++ << " " << *it++;
Whether the first it
will be incremented before the second is unspecified. 未指定第一个
it
将在第二个之前递增。
Remember, post-increment operator returns a copy of the iterator and increments the original iterator. 请记住,后递增运算符返回迭代器的副本并递增原始迭代器。 You had it twice in the same statement, So, what you were most likely having was that
it
was incremented twice before the latest copy was dereferenced first, then the former copy dereferenced second 您在同一条语句中有两次,所以,最有可能的是,在第一次取消引用最新副本之前,
it
已增加了两次,然后第二次再次引用了先前的副本。
Also see the beautiful answers to this Stackoverflow question Undefined behavior and sequence points 另请参见此Stackoverflow问题的精美答案未定义的行为和顺序点
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.