如何调整 2D C++ 向量的大小?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20047684/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 22:53:27  来源:igfitidea点击:

How can I resize a 2D C++ vector?

c++vectorresize

提问by user2878007

I have a 2D charvector:

我有一个二维char向量:

vector< vector<char> > matrix;

I will read in a matrix as an input and store it in that vector. The size of my vector is fixed and is ROW x COL. I guess I need to resize it for each row and column.

我将读取一个矩阵作为输入并将其存储在该向量中。我的向量的大小是固定的,是 ROW x COL。我想我需要为每一行和每一列调整它的大小。

How can I accomplish it without taking extra memory (resizing it correctly)?

如何在不占用额外内存的情况下完成它(正确调整大小)?

回答by leemes

Given the vector is empty, you can simply resize the outer vector with preallocated inner vectors without the need of a loop:

鉴于向量为空,您可以简单地使用预先分配的内部向量调整外部向量的大小,而无需循环:

matrix.resize(COL, vector<char>(ROW));

Alternatively, when initializingor if you want to reset a non-empty vector, you can use the constructor overload taking a size and initial value to initialize all the inner vectors:

或者,在初始化或要重置非空 vector 时,可以使用构造函数重载获取大小和初始值来初始化所有内部向量:

matrix = vector<vector<char> >(COL, vector<char>(ROW));

Depending on whether your matrix is column- or row-major, you need to swap the arguments ROWand COL. The first one (the first parameter on the outer vector) is your first dimension to access the matrix, i.e. I assumed you access it with matrix[col][row].

根据您的矩阵是列主矩阵还是行主矩阵,您需要交换参数ROWCOL。第一个(外部向量的第一个参数)是您访问矩阵的第一个维度,即我假设您使用matrix[col][row].

回答by Vlad from Moscow

    const size_t ROW = 10;
    const size_t COL = 20;
    std::vector<std::vector<char>> v;

    v.resize( ROW );

    std::for_each( v.begin(), v.end(), 
                   std::bind2nd( std::mem_fun_ref( &std::vector<char>::resize ), COL ) );

    std::cout << "size = " << v.size() << std::endl;
    for ( const std::vector<char> &v1 : v ) std::cout << v1.size() << ' ';
    std::cout << std::endl;

回答by wtom

While construction with sized vector as default value, given by @leemes, is quite an answer, there is an alternative without using an additional vector and copy ctor:

虽然由@leemes 给出的以大小向量作为默认值的构造是一个很好的答案,但还有一种替代方法,无需使用额外的向量和复制构造函数:

assert(COL >= 0);
assert(ROW >= 0);
vector<vector<char>> matrix;
for (size_t i{0}; i != COL; ++i)
{
    matrix.emplace_back(ROW);
}