0

I don't understand why I get error in the definition of the methode "add". Here is my code:

enum Colour {empty = 0, red, yellow};
class Game{
public:
 void add(size_t, Colour const&);
private:
 vector<vector<Colour>> tab;
};
void Game:: add(size_t column, Colour const& colour) {
tab[0][column].push_back(colour);
}
Ben Voigt
286k45 gold badges444 silver badges764 bronze badges
asked Apr 6, 2014 at 21:12
1
  • What is the error message? Commented Apr 6, 2014 at 21:27

3 Answers 3

3

Your member variable is a vector of vector<Colour>. If you want to add a Colour to a particular vector<Colour> at a particular index, then you need to first identify if that vector at that index is present. If so then you can add the Colour. If not you are assigning to an address that is not present.

You need something like

void Game:: add(size_t column, Colour const& colour) {
 if (column < tab.size())
 {
 // only push a new colour onto this vector if one is present.
 tab[column].push_back(colour);
 }
}

You should never access the element using the operator [] unless you are certain that an item is actually present at that location. You cannot simply assign things to vector elements if the vector size has not been allocated.

answered Apr 6, 2014 at 21:26
Sign up to request clarification or add additional context in comments.

Comments

1

If tab is uninitialized then you cannot access it by index as you are in

tab[0][column].push_back(colour);.

answered Apr 6, 2014 at 21:14

Comments

0

Check also if you use C++1X :

vector<vector<Colour>> tab; 

The no espace syntax ">>" doesn't work otherwise.

answered Apr 6, 2014 at 22:37

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.