映射C++ C 样式数组

C-style array in C++ map

本文关键字:数组 样式 C++ 映射      更新时间:2023-10-16

注意:这个问题只涉及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++容器std::array代替 C 数组。

例如

#include <iostream>
#include <array>
#include <map>
using namespace std;
int main() 
{
    const std::map<int, std::array<float,3>> colors = 
    {
        { 1, { 0.20, 0.60, 0.40 } },
        { 16, { 0.5, 0.25, 0.75 } }
    };  
    return 0;
}

为简单起见,我在示例中使用了类型 float 而不是 GLfloat

这样做:

using std;
using namespace boost::assign;
map<int, GLfloat[3]> colors  = map_list_of (1, {0.20. 0.60. 0.40}) (16, {0.5, 0.25, 0.75});

应该做这个伎俩。

也许它

不会更快,做缓存未命中。

使用排序的 std::vector 或 array<std::pair<const Key, Value>并使用 std::lower/upper_bound 查找要查找的元素。我想那会更快。