简体   繁体   English

如何在一个类中初始化向量?

[英]How do you initialize a vector within a class?

class Suduko
{
private:
    vector<vector<string>> board;
public:
    Suduko() : board(9, vector<string>(9, ".")) {}
}

Is this the only way to do it? 这是唯一的方法吗?

I've tried initializing it right where board is defined with vector<vector<string>> board(9, vector<string>(9, ".")); 我已经尝试过在用vector<vector<string>> board(9, vector<string>(9, "."));定义board的地方正确初始化它vector<vector<string>> board(9, vector<string>(9, ".")); but that doesnt work. 但这不起作用。

I also tried: 我也尝试过:

Suduko()
{
   board(9, vector<string>(9, "."));
}

and

Suduko()
{
   board = board(9, vector<string>(9, "."));
}

inside of the constructor and those didn't work either. 在构造函数内部,这些也不起作用。 So am I limited to initializing the vector to the way I did in the first example (which did work)? 因此,我是否仅限于按照第一个示例中的方法(有效)初始化矢量? Or is there another way I can do it? 还是有另一种方法可以做到?

Here are listed some ways to initialize the vector 这里列出了一些初始化向量的方法

class Suduko
{
private:
    std::vector<std::vector<std::string>> board { 9, std::vector<std::string>( 9, "." ) };
    //.....
};

class Suduko
{
private:
    std::vector<std::vector<std::string>> board = 
        std::vector<std::vector<std::string>>( 9, std::vector<std::string>( 9, "." ) );
    //.....
};

class Suduko
{
private:
    std::vector<std::vector<std::string>> board;
public:
    Suduko() : board( 9, std::vector<std::string> (9, "." ) ) 
    {
    }
};

class Suduko
{
private:
    std::vector<std::vector<std::string>> board;
public:
    Suduko() : board{ 9, std::vector<std::string> (9, "." ) } 
    {
    }
};

class Suduko
{
private:
    std::vector<std::vector<std::string>> board;
public:
    Suduko()
    {
        board.assign( 9, std::vector<std::string> (9, "." ) ); 
    }
};

To get your other attempts to work, you must use: 为了让您尝试其他工作,您必须使用:

board = vector<vector<string>>(9, vector<string>(9, "."));

You can also use: 您还可以使用:

board.resize(9);
for (auto& v : board)
{
    v.resize(9, ".");
}

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

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