c++ - 访问结构列表中的列表元素

标签 c++

以下代码创建了一个任务结构列表,其中每个任务都包含一个指令列表:

#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)   

}

根据评论:

1) 推回 task1 是否正确以获得任务列表?

2) 如何打印出任务列表中的指令元素列表? (即打印所有任务的所有说明)

最佳答案

使用 list 迭代器:

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
    }
}

关于c++ - 访问结构列表中的列表元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31165044/

相关文章:

C++ 'class' 类型重定义错误

c++ - UPX 是否神奇地将二进制文件从动态链接转换为静态链接库?

c++ - 不同步的多线程中的变量访问

c++ - 重构为独立类后,QNetworkRequest (HTTP GET) 不会触发

c++ - 在两个独立的程序之间传递信息

c++ - 在 GDB 中的捕获点停止后退出

c++ - QTextStream 向文件中写入数据

c++ - C++ 中的内存组织

c++ - std::ofstream.write() 在写入字符数组时是否比单个字符更快?

c++ - 计算缓存命中率和未命中率的程序