简体   繁体   English

C ++ push_back方法

[英]C++ push_back method

I don't understand why I get error in the definition of the methode "add". 我不明白为什么在方法“ 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);
}

Your member variable is a vector of vector<Colour> . 您的成员变量是vector<Colour>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. 如果要将Colour添加到特定索引处的特定vector<Colour> ,则需要首先确定该索引处的矢量是否存在。 If so then you can add the Colour . 如果是这样,则可以添加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. 如果尚未分配向量大小,则不能简单地将内容分配给向量元素。

If tab is uninitialized then you cannot access it by index as you are in 如果tab未初始化,则无法按索引访问它

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

Check also if you use C++1X : 还要检查您是否使用C ++ 1X:

vector<vector<Colour>> tab; 

The no espace syntax ">>" doesn't work otherwise. no espace语法“ >>”否则将不起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM