[英]Initialize vector with M elements of empty vectors c++
設置 m_data.resize(a_M) 確實有效,但我想知道為什么會發生此錯誤。
error: type 'vector<vector<double> >' does not provide a call operator
m_data(a_M);
這是 class 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++ 還是新手,所以這些小東西在互聯網上很難找到。 我真的很感激幫助!
首先,
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_m
和m_n
的類型是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)
{
}
std::vector<std::vector<float>> m_data(M);
或者
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.
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.