zstreet
zstreet

Reputation: 136

Initialize vector with M elements of empty vectors c++

Setting m_data.resize(a_M) does work but I would like to know why this error occurred.

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

This is the beginning of a class SparseMatrix. I need to initialize the row number a_M and have each element be empty. The idea is for m_data(a_M) initialize m_data to have a_M rows of empty vectors, though the error above occurred.

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

I am still new to C++ so it's these little things that are hard to come by on the internet. I really appreciate the help!

Upvotes: 1

Views: 1415

Answers (2)

R Sahu
R Sahu

Reputation: 206667

First of all,

m_data = ...;

is assignment, not initialization.

Using

m_data(a_M);
m_colIndex(a_M);

inside the body of the constructor is not right. Use

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

Since the member variables m_m and m_n are of type unsigned int, I would suggest changing the constructr to:

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

Upvotes: 1

no more sigsegv
no more sigsegv

Reputation: 526

std::vector<std::vector<float>> m_data(M);

or

std::vector<std::vector<float>> m_data;
m_data.resize(M);       //this will resize the vector
for (int i = 0; i < M; i++){
    m_data[i].resize(N);//and this will resize the empty vectors.
}

Upvotes: 0

Related Questions