1

私は構造体型を持っています

typedef struct {

Point CellLocation;
enumCell isOccupied;
Node* coveringStation;
vector< pair<float,Node*> > coveredBy;
} Cell;

次に、次のような動的入力を使用して、セルの 2D 配列を宣言しようとします。

this->Height = par("Height");
this->Width =  par("Width");

Cell **c;

c = new Cell*[Width];
for (int i = 0; i < Width; i++)
    Cell[i]= new Cell[Height];

私はこの出力を得ます:

 error: expected unqualified-id before ‘[’ token

on Cell[i]= new Cell[Width];

私は何を間違っていますか?

4

2 に答える 2

1

C++ では、C-style は必要ありません。次のように、なしでtypedef struct {...} ...a を定義できます。structtypedef

struct Cell {
   Point CellLocation;
   enumCell isOccupied;
   ....       
};

さらに、 で割り当てられた生の C スタイルの配列new[](およびで手動で解放されdelete[]、例外が安全std::vectorでない) を使用する代わりに、別の を含む のような C++ の便利なコンテナー クラスを使用できます std::vector

// 2D matrix of cells (as vector of vector)
vector<vector<Cell>> cells;

// Create the rows
for (size_t i = 0; i < Height; i++) {
    // Add an empty row
    cells.push_back(vector<Cell>());
}

// Add columns to each row
for (size_t j = 0; j < Width; j++) {
    for (size_t i = 0; i < cells.size(); i++) {
        cells[i].push_back(Cell());
    }
} 

また、cells[i][j]構文を使用して、マトリックス内の単一の要素にアクセスできます。

別の方法は、2D マトリックスをシミュレートする単一 の を使用することです。vector

// 2D matrix, simulated using a 1D vector
vector<Cell> cells(Height * Width);

// Access element at index (row, column), using:
cells[row * Width + column] = ... ;
于 2013-11-04T12:09:57.043 に答える