【问题标题】:Debugging a std::set issue调试 std::set 问题
【发布时间】:2016-04-13 14:26:17
【问题描述】:

我写了一个特殊排序的集合:

std::set<int,std::function<bool(int const&,int const&)>> ListCases;

我有问题。我无法从中删除值 9,因为调用

ListCases.find(9);

不返回可取消引用的迭代器。 但是当我使用以下循环打印该集合的所有值时:

for (auto & eVal : ListCases)
  std::cerr << " " << eVal;

我可以看到值 9 在存储的值列表中。

当我将代码隔离在单独的程序中时,该错误消失了。使用编译器选项 -fsanitize=undefined 运行 clang++,其他检查未返回任何内容。

对此有什么可能的解释?还可以考虑哪些其他调试选项?

【问题讨论】:

  • does not return a dereferencable iterator 是什么意思?
  • 您的实际代码是否使用实际函数初始化集合?否则,所有的赌注都会大打折扣。
  • 拥有一个完整的示例程序会有所帮助。 猜测 可能是您的比较函数没有正确地完成它的工作 - 您需要对键(整数)施加严格的弱排序。比较函数有什么作用?
  • 不可解引用的迭代器是一个迭代器,例如 ListCases.end()。
  • 我解决了我的问题。问题在于比较功能被破坏了。有没有办法检测到这个问题?

标签: c++ stl set


【解决方案1】:

你们提供比较功能吗?

使用这段代码

typedef std::set<int,std::function<bool(int const&,int const&)>> MySet;

MySet wListCases([](int l, int r){ return l<r; });

wListCases.insert(9);
wListCases.insert(88);
wListCases.insert(1);

auto found = wListCases.find(9);

for (auto & eVal : wListCases)
  std::cout << " " << eVal << std::endl;

如果我不提供带有 lambda [](int l, int r){ return l&lt;r; } 的函数,此程序将崩溃。否则,它会找到 9 并打印 1, 9, 88

【讨论】:

    猜你喜欢
    • 2011-07-20
    • 1970-01-01
    • 1970-01-01
    • 2011-03-01
    • 2011-09-27
    • 2017-05-31
    • 2015-08-01
    • 2016-09-04
    相关资源
    最近更新 更多