我正在尝试使用迭代器访问向量的元素。但我得到奇怪的输出。
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;
但是,在上述情况下,程序显示错误:debug assertion failed. Vector iterator not dereferencable.
这个错误特别适用于*last
。如果我只是打印*beg
那看来错了。但无法取消引用最后一个。
我遇到的迭代器的另一个问题是在增量过程中。
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
end
迭代器不是可以取消引用的迭代器。他们指出past将最后一个元素放入容器中。这是有充分理由的。但无论长短,end
迭代器实际上并不指向任何元素。如果您想要最后一个元素,则需要递减结束迭代器。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)