簡體   English   中英

C ++-[] operatorMap返回-1?

[英]C++ - [ ] operatorMap returning -1?

這是否意味着該商品在地圖中不存在? 我找不到找到答案的證明,這是真的。

這是我添加到地圖的位置:

void Shader::addAttribute(const string attribute) 
{
    attributeList[attribute] = glGetAttribLocation(program, attribute.c_str());
}

我使用以下方法添加到地圖中:

shader.addAttribute("position");

這是我從地圖檢索數據的地方:

//An indexer that returns the location of the attribute
GLuint Shader::operator [](const string attribute) 
{
    return attributeList[attribute];
}

當我在調試日志中打印該值時,我得到“位置為-1”

您要插入地圖的任何鍵的值都必須為-1。

對於:

std::map<int, int> map;
std::cout << (map [5]);

如果x(在您的情況下為5)與容器中任何元素的鍵都不匹配,則函數將使用該鍵插入一個新元素,並返回對其映射值的引用。

您在這里所做的就是將0的值分配給鍵5

映射按鍵和值工作。 您似乎不太了解它們的工作方式。 通常,您會執行以下操作:

std::map<int, int> map;
map[5] = 1; // map now contains one element, with a key of 5 and a value of 1
std::cout << (map [5]); // Prints 1

您已在此調用中將-1插入到地圖中:

glGetAttribLocation(program, attribute.c_str())

因為,如本傑明所說, “如果指定的屬性變量不是指定程序對象中的活動屬性,或者名稱以保留的前綴'gl開頭,則返回值-1”,則glGetAttribLocation返回-1。” _。 您應該執行以下操作:

int res = glGetAttribLocation(program, attribute.c_str())
if(res == -1)
{
  // Throw an exception, log an error.. Handle this error somehow.
}
else
{
  // Otherwise store the valid result.
  attributeList[attribute] = res; 
}

[]運算符總是返回某些內容,因為它創建的值對於給定的鍵不存在(否則返回鍵的現有映射)。 不管是什么,新創建的值都將使用默認構造函數作為數據類型。 這取決於您的模板參數。 顯然,您選擇的數據類型使用-1作為其默認值。

編輯:基於更新的問題, glGetAttribLocation()必須返回-1,並且該值最終出現在地圖中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM