Reputation: 718
I'd like to initialize 2-D array m_field using initialization list in the constructor. Like in this thread Creating 2-dimensional vector in class C++ , but i get errors listed below.
BoardData.h
#ifndef BOARDDATA_H
#define BOARDDATA_H
#include <vector>
class BoardData
{
public:
/** Default constructor */
BoardData(int rows, int cols);
/** Default destructor */
virtual ~BoardData();
protected:
private:
std::vector< std:vector<int> > m_field;
};
#endif // BOARDDATA_H
BoardData.cpp
#include "BoardData.h"
BoardData::BoardData(int rows, int cols) :
m_field(rows, std::vector<int>(cols,0))
{
//ctor
}
BoardData::~BoardData()
{
//dtor
}
compiler output: (gcc version 4.6.3)
BoardData.h|18|error: template argument 1 is invalid|
BoardData.h|18|error: template argument 2 is invalid|
BoardData.cpp||In constructor ‘BoardData::BoardData(int, int)’:|
BoardData.cpp|4|error: expression list treated as compound expression in mem-initializer [-fpermissive]|
BoardData.cpp|4|warning: left operand of comma operator has no effect [-Wunused-value]|
BoardData.cpp|4|error: cannot convert ‘std::vector<int>’ to ‘int’ in initialization|
||=== Build finished: 4 errors, 1 warnings ===|
Upvotes: 1
Views: 270
Reputation: 141574
std::vector< std:vector<int> > m_field;
should be
std::vector< std::vector<int> > m_field;
^
Not a very helpful error message, I agree...
Upvotes: 2
Reputation: 249153
Rather than fixing this compilation error, you should tweak your design. A rectangular array should not usually be stored as a vector of vectors, but rather as a single vector which you will index in a 2D fashion. You can use an existing library like Boost.Matrix for this, or implement it yourself:
m_field(rows*cols) // initialize
m_field[row + rows*col] // index
You can provide your own methods to index by row and column for safety. This will in the end be more efficient than the vector-of-vectors approach.
Upvotes: 0