|
| j3lps (11) | |
| Hi All, I wonder if anyone can help me with this - I'm trying to create a 2D vector. So in a header file I have: std::vector< std::vector< float > > item;What would I then put in the cpp file to make sure it is initialised, before changing the size to what I need using resize, so that it becomes, for example, a 2x2 vector of 0s? Any suggestions? J | |
Last edited on | |
| Bazzy (4111) | |
std::vector< std::vector< float > > item ( 2, std::vector<float> ( 2, 0 ) );The first argument for the vector constructor is the number of elements, the second, the value used to fill the vector http://www.cplusplus.com/reference/stl/vector/vector/ | |
| j3lps (11) | |
Thanks, but I'm not sure how to use that for what I want... Is it possible just to define the vector as a 2-D vector in the header file and then to initialise it in the cpp file? I could I suppose define it like that in the header file (could I?) and then modify it as needed in the cpp file, but I'd rather not. I've tried doing:item (2, std::vector<float> (2,0)) but it doesn't like that. So if anyone knows how to do this it'd be really helpful. J | |
| Bazzy (4111) | |
| When you define a size for a vector you are initializing it, a vector can have any size, it isn't fixed as an array is | |
| j3lps (11) | |||
| OK... but for some reason I still can't get this to work... If I'm doing something really stupid (which is likely) please tell me so... I defined the vector in the header file as: std::vector< std::vector< float > > item;And the used this (inside a function) to initialise it:
This compiles fine, but when I run the program the command prompt crashes with: Debug Assertion Failed! Expression: vector subscript out of range. Any ideas? J | |||
Last edited on | |||
| j3lps (11) | |||
Well I've found a way of doing it:
I have no idea how this works, but as it does I'm not going to complain. Thanks for your help Bazzy. | |||
| Duoas (3501) | |||
You were close before on your resizing, but line 3 was off since it didn't assign the new values. Try something like this:
Hope this helps. | |||
| gi0rgi0ne (1) | |||
This is the way that I work with vector of vectors:
simple and short. Cheers, G | |||
This topic is archived - New replies not allowed.
