奇怪的编译器错误,指出我的迭代器未定义
我正在尝试创建一个模板函数,它将迭代映射的指定键/值对,并检查函数参数中是否存在指定的任何键。
实现如下所示:
代码
template < class Key, class Value >
bool CheckMapForExistingEntry( const std::map< Key, Value >& map, const std::string& key )
{
std::map< Key, Value >::iterator it = map.lower_bound( key );
bool keyExists = ( it != map.end && !( map.key_comp() ( key, it->first ) ) );
if ( keyExists )
{
return true;
}
return false;
}
然而,无论出于何种原因,我似乎无法弄清楚为什么我的代码无法编译。相反,我得到了这些错误:
error: expected ';' before 'it'
error: 'it' was not declared in this scope
我以前遇到过这些错误,但这些通常是由于我犯的错误而导致的,这些错误很容易被发现。这里可能发生了什么?
I'm trying to create a template function which will iterate through the map's specified key/value pairs and check to see if there exists any keys specified in the function's parameters.
The implementation looks as follows:
Code
template < class Key, class Value >
bool CheckMapForExistingEntry( const std::map< Key, Value >& map, const std::string& key )
{
std::map< Key, Value >::iterator it = map.lower_bound( key );
bool keyExists = ( it != map.end && !( map.key_comp() ( key, it->first ) ) );
if ( keyExists )
{
return true;
}
return false;
}
Yet, for whatever reason, I can't seem to figure out why my code won't compile. I get these errors instead:
error: expected ';' before 'it'
error: 'it' was not declared in this scope
I've ran into these before, but these usually have been due to mistakes I've made which are easy to spot. What could be going on here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
很确定您需要一个
typename
限定符:本文 解释得相当详细。
实际上,编译器知道可能存在 std::map
std::map
变量代码>.因此,它需要的特化。 Key, Value >
对于Key
和Value
的某些值,可以包含名为iterator
statictypename
限定符来确保您实际上在这里引用的是类型,而不是某个假定的静态变量。Pretty sure you need a
typename
qualifier:This article explains in considerable detail.
Effectively, the compiler knows that there could potentially be a specialization of
std::map< Key, Value >
for certain values ofKey
andValue
which could contain astatic
variable namediterator
. So it needs thetypename
qualifier to assure it that you are actually referring to a type here and not some putative static variable.