【发布时间】:2010-08-09 23:06:34
【问题描述】:
我需要一些帮助来理解 stdext::hash_multimap 的 lower_bound、upper_bound 和 equal_range 是如何工作的(至少是 VS2005 版本)。
我有以下代码(为问题总结)
#include <hash_map>
using stdext::hash_multimap;
using std::greater;
using stdext::hash_compare;
using std::pair;
using std::cout;
typedef hash_multimap < double, CComBSTR, hash_compare< double, greater<double> > > HMM;
HMM hm1;
HMM :: const_iterator it1, it2;
pair<HMM::const_iterator, HMM::const_iterator> pairHMM;
typedef pair <double, CComBSTR> PairDblStr;
// inserting only two values for sample
hm1.insert ( PairDblStr ( 0.224015748, L"#1-64" ) );
hm1.insert ( PairDblStr ( 0.215354331, L"#1-72" ) );
// Using a double value in between the inserted key values to find one of the elements in the map
it1 = hm1.lower_bound( 0.2175 );
if( it1 == hm1.end() )
{
cout << "lower_bound failed\n";
}
it1 = hm1.upper_bound( 0.2175 );
if( it1 == hm1.end() )
{
cout << "upper_bound failed\n";
}
pairHMM = hm1.equal_range( 0.2175 );
if( ( pairHMM.first == hm1.end() ) && ( pairHMM.second == hm1.end() ) )
{
cout << "equal_range failed\n";
}
正如评论中提到的,我传入的值 (0.2175) 介于两个插入的键值 (0.224015748、0.215354331) 之间。但是代码的输出是:
lower_bound failed
upper_bound failed
equal_range failed
我是否误解了如何在地图中使用 lower_bound、upper_bound 和 equal_range?我们不能使用这些方法找到“最接近的匹配”键吗?如果这些方法不合适,您对我可以使用什么来满足我的要求有什么建议吗?
提前感谢您的帮助。
感谢@billy-oneal @dauphic 的 cmets 和编辑。我已经更新了上面的代码,使其可编译和可运行(当然,一旦包含正确的标头)。
【问题讨论】:
-
您发布的代码无法编译,您能否修复它,以便我们再次检查您是否正确使用它?例如
if( it1 = hm1.end() )和it1 = hm1.upper_bound( 0.2175 );之后的行 -
将标签更改为 visual-c++,因为标准 C++ 没有 hash_multimap 类型。
-
C++0x 等价物是 unordered_multimap
-
@dauphic。感谢您的建议。更新的代码已发布。
标签: visual-c++ stl