2011-09-12 52 views
3

我藐视变量类型如下:push_back()在一个2D矢量中,什么是正确的语法?

typedef unsigned int color[3]; 

然后我创建了一个类型的载体:

​​3210

现在,说我要一个新元素推回到这个矢量。什么是正确的语法?我的G ++不会让我这样做:

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

我本以为这是一个很好的语法:(任何建议都非常赞赏

+0

为什么,什么是G ++要反对呢? –

+0

我在生活中见过的最长的错误信息。这就像圣经的记录或其他内容。这是错误消息的第1章: 'void __gnu_cxx :: new_allocator <_Tp> :: construct(_Tp *,const _Tp&)[with _Tp = unsigned int [3],_Tp * = unsigned int(*)[3]]'' : /usr/include/c++/4.5/bits/stl_vector.h:745:6:从'void std :: vector实例化为向量<_Tp, _Alloc> :: push_back(const value_type&)[with _Tp = unsigned int [3],_Alloc = std :: allocator ,value_type = unsigned int [3]]' –

+0

part1c.cpp:66:24:从这里实例化 /usr/include/c++/4.5/ext/new_allocator.h:105: 9:错误:ISO C++禁止初始化数组new –

回答

9

不能使用原始数组作为类型的任何标准集装箱。

的类型必须分配(它们有一个隐性或显性operator =)和施工的(它们有隐性或显性的默认和拷贝构造函数)。

你可以在换你的数组类型struct允许使用与标准集装箱:

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

在这种情况下,编译器将生成隐经营者和建设者。如果你想要不同的行为,你可以定义自己的行为。

供你使用它可能是有意义的有一个初始化的构造函数:

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; 
    } 
}; 

然后你可以设置你的载体:

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

希望这有助于。

+0

+ 1提及可分配和可构造。 – Sean

+0

对于一个好的建议+1 :) –

+0

是的,这样做。 G ++现在停止了哭泣。谢谢。 –

1

您颜色类型是非常简单的,所以我会用另一种载体来定义这种类型:

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

然后:

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