runtime error Vectors

Im trying to compile a source that seems correct however, i get a runtime error any ideas? Though, i did comment out the display and it ran but nothing ran so im guessing the error is somewhere in the display function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#include "stdafx.h"
#include <iostream>
#include <vector>

using namespace std;

class MagicSquare{

private:
vector<vector<int> > magicalsquare;
void Error();
int square;
int x,y;
int size;

public:
MagicSquare(int n);
void displaySquare(void);
};

int main()
{
MagicSquare test(7);
test.displaySquare();

return 0;
}


MagicSquare::MagicSquare(int n)
{
size=n;
vector<vector<int> > magicalsquare(n,vector<int> (n));

square = n * n;
x=0;
y=n/2;
       for (int k=1; k<=square; ++k)
{
       magicalsquare[x][y] = k;
               x--;
               y++;
       if (k%n == 0)
{
       x += 2;
       --y;
}
       else
       {
       if (y==n)
       y -= n;
       else if (x<0)
       x += n;
}
}
}

void MagicSquare::Error()
{
	int size2=size/2;
    if (size-size2*2==0)
    {
        cout<<"Must input odd number."<<endl;
            exit(1);
    }
}


void MagicSquare::displaySquare(void)
{
for (int x=0; x<=size; x++)
{
for (int y=0; y<=size; y++)
cout << magicalsquare[x][y] << endl;
cout << endl;
}

}

You can't go from 0 to size like that, like arrays, vectors go from 0 to size-1.
I fixed it thanks :)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
MagicSquare::MagicSquare(int n)
{
       size=n;
       magicalVector=vector<vector<int> >(n,vector<int> (n,0)); // Uses
predefined libary vector
       square = n * n;
       x=0;
       y=n/2;
   for (int k=1; k<=square; k++)
       {
               magicalVector[x][y] = k;
               x--;
               y++;
               if (k%n == 0)
               {
                       x += 2;
                       y--;
               }
               else
               {
                       if (y==n)
                       {
                               y -= n;
                       }
                       else if (x<0)
                       {
                               x += n;
                       }
           }
       }
}

void MagicSquare::getDisplaySquare(void)  //Function Definition that creates the Magic Square
{
       cout<<"This is the Magic Square"<<endl;
       for (int x=0; x<size; x++)
       {
      for (int y=0; y<size; y++)
          {
                       cout << setw(5)<<magicalVector[x][y]; // Uses the predefined library iomanip
          }
               cout<<endl;
   }
               cout<<endl;
}
Topic archived. No new replies allowed.