2010-07-06 51 views
2

我有以下代碼。由編譯器無法識別的模板函數中的映射迭代器

template<class key,class val> 
bool has_key(key chkey,std::map<key,val> map){ 
    for (std::map<key,val>::iterator it = map.begin(); #line 13 referenced by gcc 
     it!=map.end(); ++it){ 
    if(chkey == it->first) return true; 
    } 
    return false; 
} 

GCC給我下面的錯誤。

objects.hpp: In function `bool has_key(key, std::map<key, val, std::less<_Key>, 
    std::allocator<std::pair<const _Key, _Tp> > >)': 
objects.hpp:13: error: expected `;' before "it" 
objects.hpp:14: error: `it' was not declared in this scope 

不知何故「它」沒有被初始化,Sam Hain在這裏發生了什麼?!

+0

重複包括:http://stackoverflow.com/questions/1301380/g-is-not-a-type-error HTTP://計算器。 com/questions/2841757/c-template-is-not-derived-from-type http://stackoverflow.com/questions/2931345/c-trouble-with-dependent-types-in-templates – 2010-07-06 08:47:09

+0

旁註:你確定你想通過值而不是const引用傳遞你的地圖,並使用const_iterator? – pmr 2010-07-06 09:46:32

+0

pmr,感謝您的建議。常量使用是我還沒有進入的習慣,需要養成周圍的習慣。 – Eli 2010-07-07 01:00:34

回答