| dushyantkumar1 (8) | |||
|
Hi, I am trying to declare a class matrix (containing 2D array) with following members: int d1, d2; //dimensions vector<vector<float>> p; // All values of matrix I want to put all elements of matrix in double vector. The code compiles fine. However, when I start setting the value, I get message that: .... Expression: vector subscript out of range... There is some error with function “set_value”.
| |||
|
|
|||
| shacktar (1144) | |||
This (within your constructor): vector<vector<float>> p(d2, vector<float>(d1,0)); actually defines a vector p which hides the p belonging to your matrix class!Try this instead:
| |||
|
|
|||
| johnnystarr (32) | |
| You may want to include exception handling as well. | |
|
|
|
| dushyantkumar1 (8) | |||
|
Thanks shacktar and johnystarr. shacktar, your suggestion worksed. However, for some reason, the launching of console was taking 4-5 minutes. So, rather than using resizing, I have started using:
Anyway, shacktar, can you tell me how did you figure out the source of error? johnnystarr, Since I am new to C++, I only have limited idea about exception handling and I was under impression that it's used for memory allocation. Since vector is standard STL feature, I am assuming that it must be taking care of that. Anyway, would you please show me an example in current context? Regards, | |||
|
Last edited on
|
|||
| shacktar (1144) | ||||
Well, any time the compiler sees something like (type) (identifier) ... ; it treats it as a new definition. Combine that with C++'s scoping rules and you've got yourself a lost variable.For instance:
This is precisely what was happening with your case above, where the vector p in the matrix class constructor hid the p in the scope of the whole matrix class. Seeing this comes with experience, I suppose. Also, note that vector p was already constructed here (using the vector class default constructor): vector<vector<float>> p; // All values of matrix , so it doesn't make sense to try and construct it again.
| ||||
|
|
||||