C++ 奇怪的编译器错误,说明我的迭代器未定义
我正在尝试创建一个模板函数,它将遍历映射的指定键/值对,并检查函数参数中是否存在指定的键 实现如下所示: 代码C++ 奇怪的编译器错误,说明我的迭代器未定义,c++,scope,compiler-errors,expected-exception,C++,Scope,Compiler Errors,Expected Exception,我正在尝试创建一个模板函数,它将遍历映射的指定键/值对,并检查函数参数中是否存在指定的键 实现如下所示: 代码 template < class Key, class Value > bool CheckMapForExistingEntry( const std::map< Key, Value >& map, const std::string& key ) { std::map< Key, Value >::iterator it
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;
}
我以前遇到过这些问题,但这些问题通常都是由于我犯了一些容易发现的错误。这里可能发生了什么?非常确定您需要一个
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;
}
模板
bool CheckMapForExistingEntry(const std::map&map,const std::string&Key)
{
typename std::map::迭代器it=map.lower_-bound(Key);
boolkeyexists=(it!=map.end&&!(map.key_comp()(key,it->first));
如果(存在)
{
返回true;
}
返回false;
}
解释得相当详细
实际上,编译器知道,对于
Key
和Value
的某些值,可能存在std::map
的专门化,这些值可能包含名为迭代器的静态变量。因此,它需要typename
限定符来确保您在这里实际引用的是一个类型,而不是某个假定的静态变量。@Holland代码在运行之前可能需要更多的清理。明白了吗。我刚刚解决了他报告的具体错误。可能是重复的
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;
}