简体   繁体   中英

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, ".")); 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, ".");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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