c++ - 为什么我的 vector 没有随着我对其元素所做的更改而更新?

标签 c++ oop std

<分区>

我有一个类使用 vector 来存储一组具有无符号长整数的对象。对该类的操作之一是通过将它与另一个 u_long 进行 OR 运算来更改元素的存储 u_long。

如果我在执行 OR 后立即 cout,它表明数字已更改。但是,如果我返回并cout vector 中的元素,它不会显示已进行任何更改。我在这里缺少什么?

类定义

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

关于c++ - 为什么我的 vector 没有随着我对其元素所做的更改而更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58825755/

相关文章:

c++ - STL 容器的范围插入函数在 c++11 下返回 void?

c++ - 如何在 Boost multi_index 复合键中删除?

c# - 从字符串实例化继承类

c++ - 在WSL中通过C++关闭并重新启动PC

c# - 在 C# 中,我应该使用 struct 来包装一个对象以实现额外的接口(interface)吗?

python - 什么时候重构?

c++ - C++ 中的简单正则表达式用法

c++ - 可以替换 std::allocator 允许 std::set 使用 void* 和单独的复制/释放函数吗?

c++ - 是否可以使用 wfstream 和 fstream 打开同一个文件

c++ - 如何停止 wxProgressDialog 重新调整大小?