Why does a push_back on an std::list change a reverse iterator initialized with rbegin?

前端 未结 3 1937
失恋的感觉
失恋的感觉 2020-12-01 12:24

According to some STL documentation I found, inserting or deleting elements in an std::list does not invalidate iterators. This means that it is allowed to loop over a list

3条回答
  •  南笙
    南笙 (楼主)
    2020-12-01 13:12

    I think to understand this, it's best to start by re-casting the for loop as a while loop:

    typedef std::list container;
    
    container testList;
    testList.push_back("a");
    testList.push_back("b");
    testList.push_back("c");
    
    container::reverse_iterator itList = testList.rbegin(); 
    while (itList != testList.rend()) {
        testList.push_back(*itList);
         ++itList;
    }
    

    Along with that, we have to understand how a reverse_iterator works in general. Specifically a reverse_iterator really points to the element after the one you get when you dereference it. end() yields an iterator to just after the end of the container -- but for things like arrays, there's no defined way to point to just before the beginning of a container. What C++ does instead is have the iterator start from just after the end, and progress to the beginning, but when you dereference it, you get the element just before where it actually points.

    That means your code actually works like this:

    enter image description here

    After that, you get pretty much what you expect, pushing back B and then A, so you end up with ABCCCBA.

提交回复
热议问题