C ++推送前迭代

时间:2012-10-04 23:27:07

标签: 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 :(

2 个答案:

答案 0 :(得分:6)

请注意,你的方法getComponents()正在返回一个副本,你应该返回一个引用。

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

答案 1 :(得分:5)

您的Tab::getComponents()会返回list<Component*>而不是list<Component*>&,这意味着,this->components会在返回时被复制。因此,让我们看一下代码:

list<Component*>::iterator it = activeTab->getComponents().begin(); 
// ``it'' is already INVALID here since the list returned in the above line
// is already destructed!
for (it ; it != activeTab->getComponents().end(); it++) {
    offset.x = (*it)->getX(); //``it'' is invalid
    cout << "offset.x = " << offset.x << endl;
    offset.y = (*it)->getY();
    cout << "offset.y = " << offset.y << endl;
}

取消引用迭代器it时无效。