首页 > 解决方案 > 用空向量的M个元素初始化向量c ++

问题描述

设置 m_data.resize(a_M) 确实有效,但我想知道为什么会发生此错误。

error: type 'vector<vector<double> >' does not provide a call operator
  m_data(a_M);

这是 SparseMatrix 类的开始。我需要初始化行号 a_M 并使每个元素为空。这个想法是 m_data(a_M) 将 m_data 初始化为具有 a_M 行空向量,尽管发生了上述错误。

class SparseMatrix
{
public:
  SparseMatrix();
  SparseMatrix(int a_M, int a_N);
private:
  unsigned int m_m, m_n;
  double m_zero;
  vector<vector<double> > m_data;
  vector<vector<int> >   m_colIndex;
};

SparseMatrix::SparseMatrix()
{}

SparseMatrix::SparseMatrix(int a_M, int a_N)
{
  m_m = a_M;
  m_n = a_N;
  m_zero = 0.0;
  m_data(a_M);
  m_colIndex(a_M);
}

我还是 C++ 的新手,所以这些小东西在互联网上很难找到。我真的很感激帮助!

标签: c++vector

解决方案


首先,

m_data = ...;

是赋值,而不是初始化。

使用

m_data(a_M);
m_colIndex(a_M);

构造函数的主体内部是不正确的。利用

SparseMatrix::SparseMatrix(int a_M, int a_N) : m_m(a_M),
                                               m_n(a_N),
                                               m_zero(0),
                                               m_data(a_M),
                                               m_colIndex(a_M)
{
}

由于成员变量m_mm_n是 type unsigned int,我建议将构造函数更改为:

SparseMatrix::SparseMatrix(unsigned int a_M, unsigned int a_N) : m_m(a_M),
                                                                 m_n(a_N),
                                                                 m_zero(0),
                                                                 m_data(a_M),
                                                                 m_colIndex(a_M)
{
}

推荐阅读