[英]How to convert map<int, string> from c++11 to c++98?
[英]How to convert auto (for vector<string>) from c++11 to c++98?
我在 C++11 中有這個代碼:
vector<int> stariFinale;
bool LexAnalyzer::eStareFinala(int q)
{
for (auto x : stariFinale)
if (q == x)
return true;
return false;
}
我嘗試將其轉換為 C++98,例如:
bool Analizator_L::eStareFinala(int q)
{
for (vector<int>::iterator x = stariFinale.begin(); x!= stariFinale.end(); x++)
if (q == x)
return true;
return false;
}
這給了我錯誤 no match for 'operator==' in 'q==x'
請幫忙。
現在你有了一個迭代器,而不是值,所以你必須取消引用它。 請使用前綴++,而不是后綴++。 Postfix ++ 需要創建一個臨時的,prefix ++ 不需要,比較http://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Rp-waste的執行部分。
for (vector<int>::iterator x = stariFinale.begin(); x != stariFinale.end(); ++x)
if (q == *x)
return true;
另一個需要較少代碼更改的選項是使用迭代器和舊的 x 變量:
for (vector<int>::iterator iter = stariFinale.begin(); iter != stariFinale.end(); ++iter) {
int x = *iter;
if (q == x)
return true;
}
在您的情況下更好:不要自己編寫循環,使用標准算法(比較http://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Res-lib )。 您的 function 可以使用std::find
來實現。
return std::find(stariFinale.begin(), stariFinale.end(), q) != stariFinale.end();
像這樣if (q == *x)
使用*
獲取迭代器指向的元素。
此代碼適用於 C++98 和 C++11 或更高版本:
bool LexAnalyzer::eStareFinala(int q)
{
return std::find( stariFinale.begin(), stariFinale.end(), q ) != stariFinale.end();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.