VC6 編譯下列代碼報錯 error C2679: binary '==' ...:
std::map<int, int> mmm;
std::map<int, int>::const_iterator itr = mmm.find(1234);
if (mmm.end() == itr) // 錯誤
// if (itr == mmm.end()) // 正確
G++ 可正常編譯。
map::end() 回傳 iterator (非 const),而 itr 為 const_iterator。VC6 STL 實作中,iterator::operator==(const_iterator) 未定義,但 const_iterator::operator==(iterator) 存在。因此比較順序決定成敗。
if (itr == mmm.end()) (推薦,符合慣用語)。if (mmm.end() == (MYMAP::const_iterator)itr) 或 if (static_cast<MYMAP::const_iterator>(mmm.end()) == itr)。習慣將 iterator 置於左邊:if (itr != container.end()),可避免此類相容性問題,且語意更清晰 (「迭代器是否到達終點」)。