下午好,我试图使用std :: map的lower_found成员函数。但是,它不断返回错误的答案。这是我的测试代码的摘录。请向我解释如何正确地制作std :: map下限功能。谢谢。std :: map lower_bound没有返回正确的值
class Interval {
public:
explicit Interval(int item){
mLow = item;
mHigh = item;
mStamp = 0;
}
Interval(int low, int high, int stamp = 0){
mLow = low;
mHigh = high;
mStamp = stamp;
}
Interval(void){
mLow = 0;
mHigh = 0;
mStamp = 0;
}
Interval(const Interval& r):
mLow(r.mLow),
mHigh(r.mHigh),
mStamp(r.mStamp)
{
}
bool operator<(const Interval& rhs) const{
if (mLow < rhs.mLow){
return true;
}
return false;
} // operator<
int low() const { return mLow; }
int high() const { return mHigh; }
int getStamp() const { return mStamp; }
void setLow(int lower) { mLow = lower; }
void setHigh(int higher) { mHigh = higher; }
void setStamp(int stamp) { mStamp = stamp; }
private:
int mLow;
int mHigh;
int mStamp;
}; // class Interval
int main(int Argc_,char *Argv_[]) {
int n;
Interval r;
std::map<Interval, Interval> Intervals_type;
r.setLow(0);
r.setHigh(10);
r.setStamp(1);
std::pair< Interval, Interval > tmp(r,r);
Intervals_type.insert(tmp);
r.setLow(10);
r.setHigh(20);
r.setStamp(2);
std::pair< Interval, Interval > tmp2(r,r);
Intervals_type.insert(tmp2);
r.setLow(20);
r.setHigh(30);
r.setStamp(3);
std::pair< Interval, Interval > tmp3(r,r);
Intervals_type.insert(tmp3);
r.setLow(30);
r.setHigh(40);
r.setStamp(4);
std::pair< Interval, Interval > tmp4(r,r);
Intervals_type.insert(tmp4);
n = 36;
std::map<Interval, Interval>::const_iterator it =
Intervals_type.lower_bound(Interval(n));
if (it == Intervals_type.end()){
printf(" n = %d not found\n",n);
}
return 1;
}
是什么让您认为它返回错误的结果?你能指望什么?它返回什么? – ybungalobill 2011-03-21 17:15:02
你忘了告诉我们你期待什么结果,以及你实际得到了什么。我期望它打印“未找到”,因为36比地图中的所有键都大,所以lower_bound将返回end()迭代器。 – 2011-03-21 17:17:14
你的程序打印什么,你期望打印什么? – 2011-03-21 17:17:38