C++ iterator在container的begin时和end时分别--和++会怎么样
黄舟
黄舟 2017-04-17 11:50:06
0
2
535

在C++中使用容器时,经常会对iterator赋值begin和end,如果当iterator=container.begin()时,再使用--iterator,这时iterator的值是什么代表什么意思,如果再使用++iterator,还会变成原来的值吗。

在mac os 10.10下使用clang3.5实测:

int main()
{
    std::vector<int> a;
    a.push_back(1);
    a.push_back(2);
    std::vector<int>::iterator iter = a.begin();
    --iter;
    std::cout<<*iter<<std::endl;  // 输出0(这里的值并不确定,刚开始是一个很大的负数)
    --iter;
    std::cout<<*iter<<std::endl;  // 输出0
    ++iter;
    std::cout<<*iter<<std::endl;  // 输出0
    ++iter;
    std::cout<<*iter<<std::endl;  // 输出1

    iter = a.end();
    ++iter;
    std::cout<<*iter<<std::endl;  // 输出(输出一个很大的负数)
    --iter;
    --iter;
    std::cout<<*iter<<std::endl   // 输出2
    return 0;

在clang下是可以做到越界后再返回的,并且返回后获得的值也是正确的,这是STL的标准的要求还是仅个别编译器自己的实现,并且vector是如何实现越界后能返回的。

黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

reply all(2)
阿神

The statement in the STL standard is that it is undefined, or that a certain operation will invalidate the iterator, and do not use undefined or invalid iterators.
However, the specific implementation of each compiler is different. I once conducted experiments on vector and map iterators that crossed the line on Red Hat Linux, HPUX and IBM AIX. The most serious reaction was that the program ran away...
For better compatibility of the program, listen to the standards~

PHPzhong

Subtracting

from container.begin() and adding to container.end() are both UB (undefined behavior).

Please refer to similar questions: http://stackoverflow.com/questions/19417171/stl-iterator-before-stdmap...

PS: It is not recommended to study UB, it is meaningless.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template