为什么我的向量没有随着我对其元素所做的更改而更新?

Why does my vector not update with the changes I make to its elements?

我有一个 class,它使用向量来存储一组具有无符号长整型的对象。对 class 的操作之一是通过与另一个 u_long 进行 OR 运算来更改存储的 u_long 元素。

如果我在执行 OR 后立即 cout,则表明号码已更改。但是,如果我返回 cout 向量中的元素,则不会显示已进行任何更改。我在这里错过了什么?

Class 定义

class ULBox {
public:
    ULBox(std::string s) {
        label = s;
    };

    ~ULBox(){};

    std::string getLabel(){
        return label;
    };

    void setNumber(unsigned long n) {
        number |= n;
    };

    unsigned long getNumber(){
        return number;
    }

private:
    std::string label;
    unsigned long number;
};

class BoxList {
public:
    BoxList() {};
    ~BoxList() {};

    bool addBox(std::string label) {
        ULBox newBox(label);
        boxes.push_back(newBox);
        return true;
    };

    bool updateBoxNums(unsigned long num) {
        int i = 1;
        for(auto box: boxes) {
            box.setNumber(num+i);
            std::cout << box.getNumber() << std::endl;
            i++;
        };
        return true;
    };

    void printBoxes() {
        for(auto box: boxes) {
            std::cout << box.getLabel() << ": " << box.getNumber() << std::endl;
        };
    };

private:
    std::vector<ULBox> boxes;
};

主要功能

int main(void) {
    BoxList b_list;

    b_list.addBox("first");
    b_list.addBox("second");
    b_list.addBox("third");

    b_list.updateBoxNums(2);

    b_list.printBoxes();

};

输出 output displaying 3, 4, 5 and then 0s where there should be another 3, 4, 5

当您使用

for(auto box: boxes) {
    box.setNumber(num+i);
    std::cout << box.getNumber() << std::endl;
    i++;
};

boxboxes 中项目的副本。它不是对 boxes 中项目的引用。之后你只是在修改副本。使用 auto& box.

for(auto& box: boxes) {
    box.setNumber(num+i);
    std::cout << box.getNumber() << std::endl;
    i++;
}

您没有按引用循环。那是因为 auto 永远不是一个引用,除非你明确地把它变成一个。因此,如果您打算编辑正在循环播放的实际项目,则需要通过引用来进行。这意味着像这样的代码:

auto box: boxes

应该是:

auto& box: boxes