【问题标题】:Help me understand why find returns something different than end() on std::set when set is empty帮助我理解为什么当 set 为空时 find 在 std::set 上返回与 end() 不同的东西
【发布时间】:2011-05-22 22:34:33
【问题描述】:

为什么 if-case 为真?!

 typedef std::set< boost::shared_ptr<CCall>, HasFirstQueuedLongerTime> queued_container;
    queued_container::iterator itTemp = queued.find(spCall);
    queued_container::iterator itTempEnd = queued.end();
    if(itTemp != itTempEnd ) //<-- is true

queued 是一个空的std::setspCall 是一个指向对象的共享指针。由于 queued 为空,因此 find 函数应返回等于 queued.end() 的迭代器...

我在vs2005上编译调试。我可以看到itTempitTempEnd 指向同一个地址。

感谢所有回答!

更多代码信息,在if语句之前声明如下:

queued_container queuedCalls;
const boost::shared_ptr<CCall> &spCall; //spCall is valid according to debug info.


struct HasFirstQueuedLongerTime : std::binary_function < boost::shared_ptr<CCall>, boost::shared_ptr<CCall>, bool> {
        bool operator() (const boost::shared_ptr<CCall>& lhs, const boost::shared_ptr<CCall>& rhs) const
        {
            return lhs->CreatedTime() < rhs->CreatedTime(); //returns true if lhs queued longer time than rhs
        }
    };

我真正的可执行代码:

queued_container::iterator itTemp = queued.find(spCall);
queued_container::iterator itTempEnd = queued.end();

if(itTemp != itTempEnd )
    AS_ERROR(1, "XXX", "ERROR: Already added to queue container.");
queued.insert(spCall);
CCallQueue::insert(spCall);

附言。很抱歉修改了很多内容。。

【问题讨论】:

  • 标题很模糊。我希望find 在空集中失败。但这是“失败”,如“将迭代器返回到集合结束”
  • @user521048:生成一个真正的自包含测试用例。以上没有提供足够的信息来诊断问题。
  • 很可能比较器 (HasFirstQueuedLongerTime) 不一致。
  • 作为@wilx - 显示问题的可执行代码
  • -1 您发布的附加代码甚至无效。请发布一个完整的、最小的示例来展示该问题。我们不是心灵感应者。

标签: c++ boost std


【解决方案1】:

问题解决了!

itTemp != itTempEnd

从来都不是真的! AS_ERROR 下面的函数是一个带有多个语句的“#define-function”。所以第一条语句从未被执行,但第二条语句被执行了。

【讨论】:

  • 这就是为什么你不能使用定义在哪里你可以用函数做得更好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-10-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-06
相关资源
最近更新 更多