简体   繁体   中英

How to decrement iterator in C++?

I am using c++ stl list of custom defined structs and I have an iterator that goes through that list but at one point I need to decrement and go back a few entries in the list. I tried itt-- but that just gave me a segmentation fault. Is there any other way of doing it.

I also tried this std::advance(cur_instruc, a);

Here is what the iterator looks like:

#include <iostream>
#include <string>
#include <list>

using namespace std;

typedef struct {
    int instruction_ptr;
    int token;
    std::string instruction;
    std::string value;
} decoraded_nodes;

int main () {
    std::list<decoraded_nodes> instruction_list;
    std::list<decoraded_nodes>::iterator it;
    it = instruction_list.begin();

    decoraded_nodes a;
    a.instruction_ptr = 1;
    a.token = 1;
    a.instruction = "1";
    a.value = "2";

    decoraded_nodes b;
    b.instruction_ptr = 1;
    b.token = 1;
    b.instruction = "1";
    b.value = "1";

    decoraded_nodes c;
    c.instruction_ptr = 1;
    c.token = 1;
    c.instruction = "1";
    c.value = "3";

    instruction_list.insert(it, a);
    instruction_list.insert(it, b);
    instruction_list.insert(it, c);

    bool aa = false;
    int bb = 0;

    for (std::list<decoraded_nodes>::iterator cur_instruc = instruction_list.begin(), 
        end = instruction_list.end(); 
        cur_instruc != end; ++cur_instruc) {
        cout << cur_instruc->value;

        bb++;

        if (bb == 1) {
            aa = true;
        }

        if (aa) {
            cur_instruc--;
            aa = false;
        }

    }

    return 0;
}

It's a bad idea to change loop "for" variable (in this case - an iterator) inside the loop. Try to crete new iterator inside the loop, when you need to go back and work with this newly created iterator.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM