C++推前迭代

标签 c++ for-loop iteration

我有一个包含组件列表的 Tab 类。

list<Component*> Tab::getComponents() {
    return (this->components);
}

void Tab::addComponent(Component* comp){
    this->components.push_front(comp);
}

Tab::Tab() {
    // x = 25, y = 30
Button* one = new Button(25,30,300,100, "images/button.png");
this->addComponent(one);

Button* two = new Button(75,100,300,100, "images/button.png");
this->addComponent(two);

    // x = 150, y = 150
Button* three = new Button(150,150,300,100, "images/button.png");
this->addComponent(three);  
}

现在是有问题的代码:

list<Component*>::iterator it = activeTab->getComponents().begin(); 
for (it ; it != activeTab->getComponents().end(); it++) {
    offset.x = (*it)->getX();
    cout << "offset.x = " << offset.x << endl;
    offset.y = (*it)->getY();
    cout << "offset.y = " << offset.y << endl;
}

这是 for 循环第一次迭代的输出:

offset.x = 25
offset.y = 30

但是,看到我使用了push_front(),应该是:

offset.x = 150
offset.y = 150

我做错了什么?

编辑:for 循环的第二次迭代打印垃圾...

offset.x = 16272
offset.y = 17

第三个只是打印segmentation fault :(

最佳答案

请注意您的方法 getComponents() 正在返回一个拷贝,您应该返回一个引用。

list<Component*>& Tab::getComponents() {
    return (this->components);
}

关于C++推前迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12737444/

相关文章:

SQL 从给定的零件列表中创建完整的零件列表(迭代)

python - 如何在迭代生成数据帧时保存数据帧列表?

c++ - 如何在 C++ 中转储嵌套映射以进行调试?

c# - 形成两个对象列表联合的最简单方法(包含 Int 和字符串值)

java - 删除一个实体,然后在其位置添加一个新实体

java - 为什么这个方法的返回值总是0?

c++ - 删除标准库映射

c++ - 编译 Boost 链接库 (Ubuntu)

c++ - 如何使用函数指针作为模板类的构造函数参数?

java - 如何仅打印一次嵌套 for 循环的结果