简体   繁体   中英

How do I let the user set the row size and column size of a 2D Vector?

I have a 2D vector underneath my private section; I'm trying to use the fill2dVector() function and allow a user to input the number of rows and columns. I was thinking of doing it two ways:

I tried doing something like this:

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

But, that gives me an error: numRows is not a type , and VS wants me to write a function definition for data even though there was an option to do this automatically it would lead to more errors.

The second thing I tried was to just have a vector there and just resize it to whatever the user chose as their rows and columns. When I tried doing data.resize(numRows,numCols); , I got the error: 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();

}

You could overwrite data in fill2dVector ,

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM