【问题标题】:segmentation fault while inserting into priority queue插入优先级队列时出现分段错误
【发布时间】:2009-09-26 02:38:20
【问题描述】:

我对优先队列的定义是:

template<typename Node, typename Cmp = std::less<Node> >
struct deref_compare : std::binary_function<Node*,Node*,bool>
{
    deref_compare(Cmp const& cmp = Cmp())
    : cmp(cmp) {}

    bool operator()(Node* a, Node* b) const {
        return (a->getfValue()> b->getfValue());
    }

private:
    Cmp cmp;
};

typedef deref_compare<Node,std::greater<Node> > my_comparator_t;
priority_queue<Node*,vector<Node*>,my_comparator_t> openq; 

我在做:

openq.push(myNode)

进入 3-4 个节点后,出现分段错误。

mynode 不为空。

我该如何解决?

【问题讨论】:

  • 您的代码 sn-p 非常混乱。尝试解决这个问题,我们会看到我们能为您做些什么。

标签: c++ templates segmentation-fault


【解决方案1】:

看起来familiar

不幸的是,您搞砸了模板。如果您不想要比较指针的通用解决方案,您也可以编写没有任何模板魔法的仿函数:

struct my_compare {
    bool operator()(Node const* n1, Node const* n2) const {
        return n1->getfValue() > n1->getfValue();
    }
};

priority_queue<Node*,vector<Node*>,my_compare> foo;

至于您遇到的错误。你没有给我们足够的信息。看来问题不在于您使用的仿函数。更有可能是你的代码的其余部分是罪魁祸首。

我还希望您的节点由其他数据结构(例如 std::set)管理(如在生命周期管理中),并且它们的寿命足够长。否则,很容易出现导致内存泄漏或未定义行为的错误。请记住,自动对象(那些存在于“堆栈”中的对象)在其范围离开时会被销毁,并且在修改容器后,指向存在于另一个容器中的对象的指针可能会变得无效。查看各种容器对迭代器以及何时/如果迭代器无效的保证。

【讨论】:

    【解决方案2】:

    我们需要查看插入节点的代码。听起来其中一个节点在插入后被销毁,也许您正在插入指向基于堆栈的对象的指针?

    另外,这不是问题,但您的 cmp 从未被使用过,您总是在进行大于比较。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-09-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多