2d vector subscripts going out of range even when the subscripts are in range

StackOverflow https://stackoverflow.com/questions/21869666

  •  13-10-2022
  •  | 
  •  

Question

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.

Était-ce utile?

La solution

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: enter image description here

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.

Autres conseils

C++ arrays work like this:

vector<int> v = {2, 4, 6, 8}
//index:         0  1  2  3

Therefore, the last element in the array would actually be opt[x - 1][y - 1].

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top