我有傳遞一個地圖< ...> :: iterator對象到一個函數作爲常量性&上GCC一個問題:傳遞地圖<>:迭代作爲地圖<> ::爲const_iterator&
class MyClass {
};
bool MyClass::_GetInstList(map<string,InstList>::const_iterator & it, const string & sMod)
{
cout<<"Matched\n";
it = tInstancesData.find(sMod);
if(it == tInstancesData.end()) {
cout<<"\""<<sMod<<"\" is NOT a module\n";
return false;
}
return true;
}
bool SomeFunction()
{
map<string,InstList>::iterator it;
if(! _GetInstList(it, SomeString)) return false;
it->second.Add(...); // Modifying element pointed by "it"
}
我的問題是,在Visual Studio 2010上面的代碼工作得很好,但是在GCC 4.1.2上,我得到一個錯誤,說沒有與函數調用匹配的函數_GetInstList(它,SomeString)。這個問題似乎是將迭代器轉換爲const_iterator &。
我必須把它作爲參考,因爲它在_GetInstList()內部發生了變化,調用者函數會檢查它。 (「it」指針被改變而不是一個尖銳的元素)。
另外,SomeFunction()中的「it」不能是const,因爲它改變了一個元素。
我怎樣才能解決這個問題?
編輯: 對於那些誰認爲這個問題是從迭代常量性的轉換: 如果函數原型更改爲不採取常量性作爲參考的代碼編譯好,問題是常量&。
轉換調用之前常量性?或者首先從一個const_iterator開始?或者讓代碼通用並接受任何迭代器。 –
爲什麼'_GetInstList()'需要'const_iterator'? – Adam27X
該標準說'iterator'可以轉換爲'const_iterator'。它並沒有說'iterator' *是一個* const_iterator',所以它不適用於引用它。它不會從它的const對應物繼承,所以它是需要轉換的轉換。 – leemes