2d向量下标超出范围,即使下标在范围内 [英] 2d vector subscripts going out of range even when the subscripts are in range
问题描述
所以我想写一个简单的代码,将从用户的2个字符串。然后它使用length()获取字符串的长度,并基于长度创建一个ints的矩阵(2d矢量)。然后我需要设置最后一行和最后一列的值具有2的权力值。
如果输入的字符串是happy& sad的结果矩阵应该是:
0 0 0 0 0 6
0 0 0 0 0 4
0 0 0 0 0 2
10 8 6 4 2 0
生成矩阵如下:
向量< vector< int>选择;
unsigned int x,y;
x =(sequenceOne.length())+ 1;
y =(sequenceTwo.length())+ 1;
unsigned int p,q;
opt.resize(y,vector< int>(x,0)); //调整矩阵的大小
当我尝试改变矩阵中的值时:
opt [2] [2] = 5;
它工作正常,但当我去访问最后一行最后一列如下:
opt [x] [y]
它告诉我表达式:向量下标超出范围
我认为它与获取字符串的长度用作值有关,但我不能我的生活找出为什么会导致一个问题。
我试图使下标不同的变量,不同的顺序,像opt [x-1] [y-1],但错误仍然出现。
我不确定是否重要,但我使用的是MS VS2012。
数组为0索引。 x
和 y
是数组的大小。您不能将大小值用作索引值。
例如:
a 大小为5.
a
在索引0处,e
在索引4处。e
列表。当你尝试使用5的大小作为索引,很好没有元素在索引5,你可以看到。最后一个元素将被访问 a [size-1]
。虽然记住,大小为0导致索引为-1,这是一个无效的索引。
So I am trying to write a simple code that will take in 2 strings from the users. It then takes the length of the strings using length() and creates a matrix (2d vector) of ints based on the lengths. I then need to set the values of the last row and last column to have values of powers of 2. If the entered strings are "happy" & "sad" the resulting matrix should be:
0 0 0 0 0 6
0 0 0 0 0 4
0 0 0 0 0 2
10 8 6 4 2 0
I am generating the matrix like this:
vector<vector<int>> opt;
unsigned int x, y;
x = (sequenceOne.length()) + 1;
y = (sequenceTwo.length()) + 1;
unsigned int p,q;
opt.resize(y, vector<int>(x, 0)); // resizes the matrix
When I try to change values in the matrix with:
opt[2][2] = 5;
It works fine, but when I go to access the last row last column like this:
opt[x][y]
It tells me "Expression: vector subscript out of range" I think it has something to do with the getting the length of the strings to use as the values, but I can't for the life of me figure out why that would cause an issue. I have tried making the subscripts different variables, different orders, and stuff like opt[x-1][y-1] but the error still occurs.
I'm not sure if it matters but I am using MS VS2012.
Arrays are 0 indexed. x
and y
are the size of the arrays. You can't use the size value as an index value.
For instance:
a
is of size 5. "a"
is at index 0, "e"
is at index 4. "e"
is the 5th element in the list. When you try to use the size of 5 as the index, well there is no element at index 5, as you can see. The last element would be accessed a[size - 1]
. Though remember, size of 0 results in an index of -1, which is an invalid index.
这篇关于2d向量下标超出范围,即使下标在范围内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!