【问题标题】:struct inside of array not being updated数组内部的结构未更新
【发布时间】:2022-01-10 16:55:26
【问题描述】:

我有一个包含结构数组的类,我想在我的程序中使用方法 mark_value 进行修改,但由于某种原因,这些结构没有被更新。

自从我使用 c++ 以来已经有一段时间了,所以也许我错过了一些基本的东西,抱歉。我的代码如下所示:

class BingoTable {
private:
    int table_size = 5;
    std::vector<Number> numbers;

    BingoTable(std::vector<std::string> lines) {
       // populates the numbers vector.
    }

    void mark_value(int value) {
        int i;
        for (i = 0; i < this->numbers.size(); ++i) {
            if (this->numbers[i].value == value) 
                this->numbers[i].marked = true;
        }
    }

对于 mark_valuees,我也尝试了以下代码:

 void mark_value(int value) {
    for(Number n: this->numbers) 
        if (n.value == value)
            n.marked = true
    }

感谢任何人花时间在这里:D

编辑:

分享整个代码:

struct Number {
    int value;
    bool marked;
};

// constructor
BingoTable(std::vector<std::string> lines) {
        Number n;
        for (std::string line: lines) {
            std::string parsed;
            for (char s: line) {
                if ((s == ' ' || s == '\0') && parsed.size() > 0) {
                    n.value = std::stoi(parsed);
                    n.marked = false;
                    this->numbers.push_back(n);
                    parsed.clear();
                } else {
                    parsed.push_back(s);
                }
            }
            n.value = std::stoi(parsed);
            n.marked = false;
            this->numbers.push_back(n);
            parsed.clear();
        }
    };




 
//main
    std::vector<string> lines = ["1 7 5"]
    std::vector<int> values = [1, 5]
    for(int i: values)
    for(BingoTable table: tables) {
        table.mark_value(i);
        for (Number n: table.numbers)
            std::cout << n.marked;
        std::cout << std::endl;

【问题讨论】:

  • for(Number n: this-&gt;numbers) 应该是 for(Number&amp; n: this-&gt;numbers) 。现在您正在创建向量的每个元素的副本
  • 我试过了,但迭代之间没有更新数组,我在每次迭代后打印整个数组标记的值,最后更新的值打印为 1,但所有之前的标记值都没有更新。 @UnholySheep
  • 您必须提供正确的minimal reproducible example 然后,我上一条评论中的更改将解决您提到的问题
  • 我添加了更多代码,我认为这足以让您尝试解决问题,如果您需要更多帮助,请告诉我
  • 这不是“整个代码”,也不是可重现的示例。我们无法编译它。

标签: c++ vector struct


【解决方案1】:

您的示例不完整,但您似乎正在访问数据的副本,而不是每次都访问原始数据。

试试:

for(BingoTable &table: tables) {

for (Number &n: table.numbers)

BingoTable(std::vector<std::string> &lines) {

【讨论】:

  • +1。只是为了扩展一点解释,在显式或隐式赋值中使用对象的任何地方(在循环中以及作为参数传递的地方),如果我们不通过 &amp; 使用引用,则会创建一个副本操作员。代码修改了副本,原始对象保持不变。
  • @roccobaroccoSC 或 &amp;&amp;decltype(auto)
猜你喜欢
  • 1970-01-01
  • 2023-02-18
  • 1970-01-01
  • 2022-01-07
  • 1970-01-01
  • 1970-01-01
  • 2011-12-28
  • 2013-10-27
  • 1970-01-01
相关资源
最近更新 更多