迭代器无法正确访问问题 [英] iterators can't access problems properly
问题描述
我试图使用迭代器访问向量的元素。但我得到奇怪的输出。
I am trying to access the element of a vector using the iterator. But I get strange outputs.
std::vector<int> ivec{ 7, 6 , 8, 9} ;
std::vector<int>::iterator beg = ivec.begin();
std::vector<int>::iterator last = ivec.end();
std::cout << *beg << *last << std::endl;
但是,在上面的例子中程序显示错误:调试断言失败。矢量迭代器不是dereferencable。
,此错误特别适用于 * last
。如果我只打印 * beg
,那似乎错了。但是不能取消引用最后一个。
But, In the above case the program shows me error: debug assertion failed. Vector iterator not dereferencable.
and this error is particularly for *last
. If I just print *beg
that seems to wrong fine. But can't dereference the last one.
我用迭代器得到的其他问题是在增量期间。
Other problem I get with iterator is during increment.
std::vector<int>::iterator beg = ivec.begin();
cout << *(beg++) ; // in this case it prints me value of 7
cout << *(++beg) ; // in this case it print me the right value of second place i.e. is 6
cout << *(beg+=1) ; // in this case we also print the second value i.e. 6
推荐答案
对于你的第一个例子, std :: vector< T> :: end
指向实际的最后一个元素之后的理论元素,因此取消引用它没有任何意义。它主要用于检查你在循环中超过向量结尾的时间。
For your first example, std::vector<T>::end
points to the theoretical element after the actual last element, so dereferencing it does not make sense. It is primarily used for checking when you have got past the end of the vector in a loop.
对于你的第二个例子,结果如你所料:
For your second example, the results are as you would expect:
cout << *(beg++) ; //increments beg after dereferencing
cout << *(++beg) ; //increments beg before dereferencing
cout << *(beg+=1) ; //dereferences the result of adding one to beg
这篇关于迭代器无法正确访问问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!