vector subscript out of range array subscript out of range error

When using a two-dimensional array vector, generating vector subscript out of rangeerrors, check the

Later, I didn’t find the array subscript out of bounds problem. Baidu took a look and found that the array was not initialized.

Assignment, there is no allocated space, so it cannot be accessed by subscript.

There are two solutions. One is to allocate space for the array when initializing the array, and assign all values ​​to 0.

vector<vector<int> > myvec(n, vector<int>(n, 0));

Another is the use of vector.push_backadditive elements, without the use of standard access method assignment.

Here is the program that went wrong:

//构造杨辉三角
class Solution {
    
    
public:
	vector<vector<int>> generate(int numRows) {
    
    
		vector<vector<int>> res(numRows);
		if (numRows < 1) return res;
		for (int i = 0; i < numRows; i++)
		{
    
    
			for (int j = 0; j <= i; j++)
			{
    
    
				if (j == 0 || j == i)
					res[i][j] = 1;
				else
					res[i][j] = res[i - 1][j - 1] + res[i - 1][j];
			}
		}
		return res;
	}
};

Adopt vector.push_backthe way of solving the problem.

//构造杨辉三角
class Solution {
    
    
public:
	vector<vector<int>> generate(int numRows) {
    
    
		vector<vector<int>> res(numRows);
		if (numRows < 1) return res;
		for (int i = 0; i < numRows; i++)
		{
    
    
			for (int j = 0; j <= i; j++)
			{
    
    
				if (j == 0 || j == i)
					res[i].push_back(1);
				else
					res[i].push_back(res[i - 1][j - 1] + res[i - 1][j]);
			}
		}
		return res;
	}
};

Guess you like

Origin blog.csdn.net/qq_33898609/article/details/109306525