如何调整矢量大小(仅行)

How do I resize vector (only rows)

本文关键字:仅行 调整 何调整      更新时间:2023-10-16

如何在 2D 向量中仅调整行的大小?

vector< vector<int> > matrix;
matrix.resize( num_of_row , vector<int>("I don't know how big the cols ") );

如果matrix不为空,则可以从矩阵的一行中获取列数。

如果matrix为空,则还需要提供列数作为函数的输入。

if ( matrix.size() > 0 )
{
size_t num_of_col = matrix[0].size();
matrix.resize(num_of_row, std::vector<int>(num_of_col));
}
else
{
matrix.resize(new_num_of_row, std::vector<int>(new_num_of_col));
}

如果matrix为空并且函数没有new_num_of_col,您能做的最好的事情就是创建一个所有行都为空的矩阵。

matrix.resize(new_num_of_row);

您可以在调整大小之前保存现有列计数。像这样:

auto num_of_col = matrix[0].size();
matrix.resize(new_num_of_row, std::vector<int>(num_of_col));

matrix.resize(new_no_col,std::vector<int>(old_no_col));