简体   繁体   English

cpp使用向量编译错误初始化二维数组

[英]cpp initialize 2-D array using vectors compilation error

I'd like to initialize 2-D array m_field using initialization list in the constructor. 我想使用构造函数中的初始化列表初始化二维数组m_field。 Like in this thread Creating 2-dimensional vector in class C++ , but i get errors listed below. 就像在该线程中在类C ++中创建二维矢量一样 ,但是出现以下错误。

BoardData.h 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 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) 编译器输出: (gcc版本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 ===|
std::vector< std:vector<int> > m_field;

should be 应该

std::vector< std::vector<int> > m_field;
                 ^

Not a very helpful error message, I agree... 我同意这不是一个非常有用的错误消息...

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. 矩形数组通常不应存储为向量的向量,而应存储为将以2D方式索引的单个向量。 You can use an existing library like Boost.Matrix for this, or implement it yourself: 您可以为此使用现有的库,例如Boost.Matrix,也可以自己实现它:

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. 最后,这将比矢量方法更有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM