注意:这个问题仅涉及 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]
作为值类型,不满足关联容器的以下要求。
- 它不是
EmplaceConstructible
。 - 它不是
CopyInsertable
。 - 它不是
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/