如何调整2D C ++向量的大小? [英] How can I resize a 2D C++ vector?

查看:62
本文介绍了如何调整2D C ++向量的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个2D char 向量:

vector< vector<char> > matrix;

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

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.

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

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

推荐答案

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

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 initializing or 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:

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

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

Depending on whether your matrix is column- or row-major, you need to swap the arguments ROW and 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].

这篇关于如何调整2D C ++向量的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆