【问题标题】:Unexpected changes in std::vector [closed]std::vector 中的意外变化 [关闭]
【发布时间】:2013-05-13 18:50:18
【问题描述】:

代码如下:

typedef struct Triplet
{
    double value;
    int row;
    int column;
};

class Matrix
{
public:
//Some methods
double specialMethod(/*params*/);
private:
    std::vector<Triplet> elements;
    int nRows;
    int nColumns;
};

specialMethod 被调用后,Matrix.element 中的值已损坏。但是除了像这样迭代之外,他们什么也没做:

std::vector<Triplet>::iterator it;
std::vector<Pair> buff;
for (it = this->elements.begin(); it != this->elements.end(); ++it)
    {

        if (it->column = n)
        { 
            Pair p;
            p.key = it->row;
            p.value = it->value;
            buff.push_back(p);
        }
    }

不知道从哪里开始寻找错误。

【问题讨论】:

  • 您可以从打开编译器警告开始并修复它指出的问题,这可能是问题的原因
  • 在 Visual Studio 中,如果您将警告级别设置为 3 以上,编译器会在条件赋值时发出警告。下次开始的好方法。
  • kotlomoy & Jonathan,谢谢,下次会用到。

标签: c++ struct stdvector


【解决方案1】:
  if (it->column = n)

应该是:

 if (it->column == n)

你是在做比较而不是赋值。

【讨论】:

  • @PavelOganesyan 不客气。
  • 将在 12 分钟内批准答案,所以不要让我现在这样做。
  • @PavelOganesyan 非常感谢您接受答案,如果它确实解决了您的问题。
【解决方案2】:

如果可能,将 n 定义为 const 值并在 if 指令中反转比较顺序 - 就像这样:if(n == it->column)。 编译器将帮助您找到类似的错误。

请注意,如果打开更高的警告级别,编译器无论如何都会警告此类错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-03
    • 2011-06-22
    • 1970-01-01
    • 2021-12-02
    • 1970-01-01
    • 1970-01-01
    • 2011-10-02
    • 2021-04-14
    相关资源
    最近更新 更多