gpt4 book ai didi

c++ - std::map lower_bound 没有返回正确的值

转载 作者:太空狗 更新时间:2023-10-29 11:30:28 26 4
gpt4 key购买 nike

下午好,我正在尝试使用 std::map lower_found 成员函数。但是,它一直返回错误的答案。这是我的测试代码的摘录。请向我解释如何使 std::map 下限正常运行。谢谢。

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;
}

最佳答案

std::mapoperator < 比较只有,所以它只知道 Interval::mLow , 有效地将所有区间视为 [mLow, ∞).您使用了错误的容器。可以用 map 来做,但更难。使用 Boost.Icl相反。

编辑:STL 中为此目的最好的东西是 std::multi_set。按正确的终点排序间隔:

     bool operator<(const Interval& rhs) const{     
return mHigh < rhs.mHigh;
}

现在你可以这样做:

std::multi_set<Interval> cont;
cont.insert(Interval(0,10,1));
cont.insert(Interval(10,20,2));
cont.insert(Interval(20,30,3));
cont.insert(Interval(30,40,4));

std::multi_set<Interval>::const_iterator iter = cont.lower_bound(Interval(36));
if(iter == cont.end() || iter->low() > 36)
// not found
else
// found

关于c++ - std::map lower_bound 没有返回正确的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5381117/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com