奇怪的编译器错误,指出我的迭代器未定义。

3
我将尝试创建一个模板函数,该函数将迭代地遍历映射(map)中指定的键值对,并检查是否存在函数参数中指定的任何键。
实现如下所示:
代码
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

我以前遇到过这些问题,但通常是由于我自己犯的易于发现的错误。这里可能出了什么问题?


1个回答

5
很确定你需要使用“typename”限定符:
template < class Key, class Value >
bool CheckMapForExistingEntry( const std::map< Key, Value >& map, const std::string& key )
{
    typename 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;
}

这篇文章进行了详细解释。

实际上,编译器知道对于某些特定的KeyValue值,std::map< Key, Value >可能会有一个名为iterator的静态变量。因此,它需要使用typename关键字来确保您实际上是在引用类型,而不是某个虚构的静态变量。


@Holland 这段代码在运行前需要进行一些清理。请参考 http://ideone.com/lcsQB - Lambdageek
好的观点。我只是解决了他报告的特定错误。 - mwigdahl

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接