blueprint
blueprint

Reputation: 70

Access list elements in list of structs

The following code creates a list of Task structs, where each task contains a list of instructions:

#include <list>

using namespace std;
/////////////////////////////////////////////
struct Insts{
    int dest, src1, src2, imm;
    bool is_mem, is_int;
    string op;  
};

struct Task{
    int num_insts, task_id;
    list<Insts> inst;
};
//////////////////////////////////////

list<Task> tasks; //Global list of tasks

//////////////////////////////////////

int main(){
    Insts tmp_inst;
    Task task1;

    tmp_inst.dest = 9; tmp_inst.src1 = 3; tmp_inst.src2 = 2; 
    tmp_inst.imm = 11;  tmp_inst.op = "add";

    task1.num_insts = 1;
    task1.task_id = 1;
    task1.inst.push_back(tmp_inst);

    //... add more instructions and updating .num_insts

    //pushback task1 into global "tasks" list
    tasks.pushback(task1); //????

    //>>print() all insts for all tasks? (Debugging purposes)   

}

As per the comments:

1) is pushing back task1 correct to obtain a list of tasks?

2) How can I print out the list of instruction elements within the list of tasks? (i.e. print all the instructions for all tasks)

Upvotes: 1

Views: 1850

Answers (1)

Ediac
Ediac

Reputation: 853

Use the list iterator:

for (std::list<Task>::iterator it = tasks.begin(); it != tasks.end(); ++it){
    // `it` is a reference to an element of the list<Task> so you must dereference
    // with *it to get the object in your list

    for (std::list<Insts>::iterator it2 = it->inst.begin(); it2 != it->inst.end(); ++it2){
       // it2 will now reference the elements within list<Insts> of an object Task
    }
}

Upvotes: 1

Related Questions