[英]C-style array in C++ map
注意:此問題僅與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 ++容器std::array
。
例如
#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查找要查找的元素。 我想那會更快。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.