Reputation: 1881
I need a variable which will hold 22 pairs of ints (positions in a grid) so I was thinking of having a matrix array. So in my header file is:
int points[22][2];
but when I put the following in the constructor of the object:
this->points = {{1,2},{2,3},...};
It says "must be a expression must be a modifiable lvalue" I've tried using the const keyword and making it a pointer in the header file as described here Expression must be a modifiable L-value
I've also tried creating a separate 2d array and then assigning it but this doesn't work either.
int points2 = {{1,2},{2,3},...};
this->points = points2;
I'm used to Java and I'm not too experienced with C++. There is a default constructor that will assign the values as above and a constructor which will have the matrix as parameter.
The following does work:
this->point[1][1] = 4;
But this means I can't pass another value as a parameter and I end up with 44 lines of messy code in the default constructor! And I was going to use a struct with 2 ints and put them in a vector put that seems like a bit of an overkill and would mean I need 22 vector inserts before I even called the constructor with the manual values and I just thought there must be a better way :)
Thanks
Upvotes: 1
Views: 261
Reputation: 3971
Since you're using C++, a much better choice would be to use a vector
of pair
s of int
s.
Declare it like this:
std::vector<std::pair<int, int> > points;
In your constructor you can specify size at initialization
: points(22),
or set it at any point like this:
points.resize(22);
You can access individual coordinates with
points[1].first = 1;
points[1].second = 44;
or with
points[1] = make_pair(1, 44);
or you can build it up without having to worry about exceeding its allocated size with
points.push_back(make_pair(1, 44));
etc
Upvotes: 1
Reputation: 146968
The fundamental cause of your problem is that arrays do not count as real values in C++. They are substandard in many ways- one of which you have just encountered. Any normal type would work as you expect. Unfortunately, to those of us who are not language experts, the error Visual Studio throws is incredibly unhelpful.
You must create an array on the stack and then manually loop through and assign all the values.
Upvotes: 0