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);
}
-
What is the error message?Ben Voigt– Ben Voigt2014年04月06日 21:27:25 +00:00Commented Apr 6, 2014 at 21:27
3 Answers 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.
Comments
If tab is uninitialized then you cannot access it by index as you are in
tab[0][column].push_back(colour);.
Comments
Check also if you use C++1X :
vector<vector<Colour>> tab;
The no espace syntax ">>" doesn't work otherwise.