开发者

push_back() in a 2d vector, what is the right syntax?

I have defied a variable type as follows:

typedef unsigned int color[3];

I then created a vector of that type:

vector<color> RGB;

N开发者_如何学JAVAow, say I want to push back a new element to this vector. What is the right syntax? My g++ won't let me do something like:

color temp = {255, 255, 255};
RGB.push_back(temp);

Which I thought would be a good syntax :( Any suggestions are very much appreciated


You can't use raw arrays as types for any of the standard containers.

The types must be assignable (they have either an implicit or explicit operator =) and constructable (they have either implicit or explicit default and copy constructors).

You could wrap your array type in a struct to allow use with the standard containers:

struct my_colour_array
{
    unsigned int colours[3];
};

In this case, the compiler will generate implicit operators and constructors. If you want different behaviour you can define your own.

For your use it might make sense to have an initialising constructor:

struct my_colour_array
{
    unsigned int colours[3];

// initialising constructor
    my_colour_array (unsigned int r, unsigned int g, unsigned int b)
    {
        this->colours[0] = r;
        this->colours[1] = g;
        this->colours[2] = b;
    }
};

Then you can setup your vector:

std::vector<my_colour_array> myvector;
// push data onto container via a temporary
myvector.push_back(my_colour_array(0,255,0));
// etc

Hope this helps.


You color type is pretty simple, so I would use another vector to define this type:

typedef vector<int> color;
vector<int> temp(3,0); // 3 ints with value 0
temp[0] = 255;
temp[1] = 255;
temp[2] = 255;

and then:

vector<color> RGB;
RGB.push_back(temp);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜