c++ - C++ 映射中的 C 风格数组

标签 c++ arrays dictionary

注意:这个问题仅涉及 C++ 中的映射和数组。碰巧我正在使用 OpenGL,所以那些没有 OpenGL 知识的人不应该阻止继续阅读。

我正在尝试将 C 样式数组放入 C++ std::map 中,以便稍后在设置颜色时使用。

const map<int, GLfloat[3]> colors = { // 
    {1, {0.20. 0.60. 0.40}},          //
    ...                               // This produces an error.
    {16, {0.5, 0.25, 0.75}}           //
};                                    //

...

int key = 3;
glColor3fv(colors.at(key));

这不会编译,因为:

Semantic Issue
Array initializer must be an initializer list

...但我确实指定了一个初始值设定项列表,不是吗?为什么这不起作用?

最佳答案

类型GLfloat[3]作为值类型,不满足关联容器的以下要求。

  1. 它不是EmplaceConstructible
  2. 它不是CopyInsertable
  3. 它不是CopyAssignable

更多详情请访问 http://en.cppreference.com/w/cpp/concept/AssociativeContainer .

您可以创建一个帮助器类来帮助您。

struct Color
{
   GLfloat c[3];
   GLfloat& operator[](int i) {return c[i];}
   GLfloat const& operator[](int i) const {return c[i];}
};

const std::map<int, Color> colors = {
    {1, {0.20, 0.60, 0.40}},
    {16, {0.5, 0.25, 0.75}}
};  

关于c++ - C++ 映射中的 C 风格数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27199551/

相关文章:

c++ - 读入一个对象,该对象是另一个对象 C++ 的数据成员

C++模板函数指针

C++ - 用字符替换 "_"

c++ - 字符数组作为 C++ 映射中的值

c++ - 打印一个 map 的值,它有两个字符串作为键和 vector 作为值

c++ - 输入层类型 : ImageData in windows caffe cpp giving Blank Output

c++ - C++与OpenCV的图像对比方法

c - 声明一次数组 C

java - 数组未接收单选按钮值

ios - 从 Swift 中的字典中读取 - 不工作