std::vector中的意外更改

Unexpected changes in std::vector

本文关键字:意外 vector std      更新时间:2023-10-16

代码如下:

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在矩阵中得到调用值后。元素被破坏了。但是除了像这样迭代之外,对它们没有做任何事情:

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

不知道从哪里开始找错误

  if (it->column = n)
应:

 if (it->column == n)

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

请注意,如果打开了更高的警告级别,编译器无论如何都会对这种错误发出警告。