gdagger
gdagger

Reputation: 69

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?

Upvotes: 0

Views: 190

Answers (2)

Vlad from Moscow
Vlad from Moscow

Reputation: 310930

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

Upvotes: 3

Neil Kirk
Neil Kirk

Reputation: 21763

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

Upvotes: 0

Related Questions