0

行と列の数を取り、オブジェクト「セル」のデフォルト値でベクトルのベクトルを初期化し、そのベクトルへのポインターを返す関数があります。

//Cell class
class cell{
public:
    int cost, parent;
    cell(int cost = 0, int parent = 0) : cost(cost), parent(parent){}
}

//The initialisation function
vector<vector<cell> >*  init_table(int n_rows, int n_cols){
    //Error line
    vector<vector<cell> >* table = new vector<vector<cell>(n_cols)> (n_rows);

    //Some(very few) special cells need a different value so I do that here

    return table; //Return the pointer
}

コンパイラは (n_cols)> (n_rows) を > 操作のように解決し、セル オブジェクトの n_cols コピーとベクトル オブジェクトの n_rows コピーを作成しないようです。ベクター内のデフォルト値のセルを手動でループしてプッシュせずにベクターを初期化するにはどうすればよいですか?

4

2 に答える 2

1

通常、C++ コンパイラには戻り値の最適化機能があるため、単純に実行できます。

vector<vector<cell> >  init_table(int n_rows, int n_cols)
{
    return vector<vector<cell> >(n_rows, vector<cell>(n_cols));
}

と書く

vector<vector<cell> > my_table = init_table(int n_rows, int n_cols);

ベクトルを「新規」化するのと同じくらい効率的ですが、これはより安全です。

于 2012-12-08T08:59:32.263 に答える
0

ああ、今わかりました。次のようなコンストラクターを介して、外側のベクターを内側のベクターで初期化する必要があります

vector<vector<cell> >* table = new vector<vector<cell> > (n_rows, vector<cell>(n_cols));

テンプレートパラメータとしてではありません。それは今働いています。

于 2012-12-08T08:16:04.037 に答える