[英]How do you initialize a vector within a class?
class Suduko
{
private:
vector<vector<string>> board;
public:
Suduko() : board(9, vector<string>(9, ".")) {}
}
这是唯一的方法吗?
我已经尝试过在用vector<vector<string>> board(9, vector<string>(9, "."));
定义board的地方正确初始化它vector<vector<string>> board(9, vector<string>(9, "."));
但这不起作用。
我也尝试过:
Suduko()
{
board(9, vector<string>(9, "."));
}
和
Suduko()
{
board = board(9, vector<string>(9, "."));
}
在构造函数内部,这些也不起作用。 因此,我是否仅限于按照第一个示例中的方法(有效)初始化矢量? 还是有另一种方法可以做到?
这里列出了一些初始化向量的方法
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, "." ) );
}
};
为了让您尝试其他工作,您必须使用:
board = vector<vector<string>>(9, vector<string>(9, "."));
您还可以使用:
board.resize(9);
for (auto& v : board)
{
v.resize(9, ".");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.