![]() |
| ||
| Vector of vectors & magic square issues Hello folks I'm trying to simulate a magic square algorithm, but having some problems. The program successfully creates the magic square, but when I'm trying to print it, the VC2005 compiler says "vector subscript out of range", which it shouldnt be. Any help would be appreciated. Cheers Here's the code: |
| ||
| Re: Vector of vectors & magic square issues Where is the variable sz defined and given avalue, and what value does it have in relation to dimensions of the the variable called data? Also, please indent code so it is easier to read. |
| ||
| Re: Vector of vectors & magic square issues Here's my try for the properly indented code with the display function properly pasted. Sorry for the inconveniences, but pasting it from VC doesn't preserve whitespace, whis is very annoying! |
| ||
| Re: Vector of vectors & magic square issues Two problems I can see: • Your memory allocation is not proper. Each of your rows share a common vector variable because of the stmt: vector<int> v(n);Here the memory for each inner row is getting allocated only once and your two dimensional matrix gets populated with the same vector. You need to change it to: vector<vector<int> > data(n,vector<int> (n));So that the memory allocation occurs for each row rather than only once for all rows. • Your logic is skewed. The line : i=0;is bound to produce an out of bounds error since you are decemeneting i which already is zero, resulting in its value becoming -1, which is not a valid index. Better use size_t instead of int for index variables to make sure you don't invade the out of bounds exception land. (assigning -ve values to such variables leads to a warning which is fairly easy to decode). |
| ||
| Re: Vector of vectors & magic square issues Quote:
Ok, thanks a lot man. I've finally fixed my code, and the proram works fine now. Thanks for all the help :) Cheers! |
| All times are GMT -4. The time now is 1:11 am. |
Forum system based on vBulletin Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
©2003 - 2009 DaniWeb® LLC