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

在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是如何实现越界后能返回的。

黄舟
黄舟

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

全部回覆(2)
阿神

STL標準中的說法是未定義,或者說是某某操作會讓迭代器失效,並且不要使用未定義或失效的迭代器。
但各家編譯器的具體實作各不相同,我曾經做過vector和map的迭代器在紅帽Linux、HPUX和IBM AIX上越界後的實驗,最嚴重的反應是程式直接跑飛了…
為了程序更好的相容性,聽標準的話~

PHPzhong

container.begin() 做減,和對 container.end() 做加,都是 UB (未定義行為)。

請參考類似問題:http://stackoverflow.com/questions/19417171/stl-iterator-before-stdmap...

PS: 建議不要去研究 UB, 沒有意義。

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板