【问题标题】:C-style array in C++ mapC++ 映射中的 C 样式数组
【发布时间】:2015-01-27 18:08:38
【问题描述】:

注意:这个问题只涉及 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

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

【问题讨论】:

    标签: c++ arrays map


    【解决方案1】:

    问题是数组既没有复制构造函数也没有复制赋值运算符。使用具有复制构造函数和复制赋值运算符的标准 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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • @MarcusMcLean,您可以将GLfloat* data() { return c; } 添加到Color 以使其与其他需要GLfloat* 的功能一起使用。
      • struct Color 本质上是std::array&lt;GLfloat,3&gt;
      • @EmilioGaravaglia,同意。
      【解决方案3】:

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

      使用已排序的 std::vector 或 array&lt;std::pair&lt;const Key, Value&gt; 并使用 std::lower/upper_bound 查找您要查找的元素。我猜这样会更快。

      【讨论】:

      • 那么,对此做出否定投票的理由是什么?
      【解决方案4】:

      这样做:

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

      应该做的伎俩。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-09-09
        • 2011-10-04
        • 2012-04-17
        • 2015-10-02
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多