gpt4 book ai didi

c++ - 如何让用户设置 2D Vector 的行大小和列大小?

转载 作者:行者123 更新时间:2023-12-02 10:04:14 25 4
gpt4 key购买 nike

我的私有(private)部分下方有一个 2D vector ;我正在尝试使用 fill2dVector()功能并允许用户输入行数和列数。我正在考虑以两种方式做到这一点:

我试着做这样的事情:

private
size_t numRows, numCols;
vector<vector<int> > data(numRows,vector<int> (numCols,0));

但是,这给了我一个错误: numRows is not a type , 并且 VS 希望我为数据编写一个函数定义,即使有一个选项可以自动执行此操作,这会导致更多错误。

我尝试的第二件事是在那里只放一个 vector ,然后将其大小调整为用户选择的行和列。当我尝试做 data.resize(numRows,numCols); ,我得到了错误: no instance of overloaded function "std::vector<_Ty, _Alloc>::resize [with _Ty=std::vector<int, std::allocator<int>>, _Alloc=std::allocator<std::vector<int, std::allocator<int>>>]" matches the argument list
#include <iostream>
#include <vector>

class Matrix
{
public:
Matrix();

void fill2dVector();

void display2dVector() const;

private:
size_t numRows, numCols;
std::vector<std::vector<int> > data;
};

Matrix::Matrix()
{
}

void Matrix::display2dVector() const
{
}

void Matrix::fill2dVector()
{
std::cout << " How many rows? ";
std::cin >> numRows;

std::cout << "How many columns? ";
std::cin >> numCols;
std::cout << std::endl;

std::cout << "*** numRows = " << numRows << ", " << "numCols = " << numCols << std::endl;
data.resize(numRows,numCols);
std::cout << "*** rowSize = " << data.size() << ", " << "colSize = " << data[0].size() << std::endl;
}

int main()
{
std::cout << "Enter the size of the matrix:" << std::endl;

Matrix matrix;
matrix.fill2dVector();

}

最佳答案

您可以覆盖 datafill2dVector ,

data = vector<vector<int>>(numRows, vector<int>(numCols, 0));  

关于c++ - 如何让用户设置 2D Vector 的行大小和列大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61036289/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com