【问题标题】:Segmentation fault trying to dereference an iterator尝试取消引用迭代器的分段错误
【发布时间】:2014-02-03 22:12:15
【问题描述】:

我正在尝试使用 std::max_element 找到向量的最大值。当我运行程序时,我得到一个分段错误,我认为这与 std::end 越过向量的末尾有关?我尝试将其更改为 std::end(tempdata)-1) 但无济于事。

    auto max = std::max_element(std::begin(tempdata), std::end(tempdata));
    std::ofstream maxcurrent("maxcurrent.txt", std::ios::app);
    maxcurrent << v << std::setw(15) << *max << std::endl;

看了this answer 我不明白为什么我的不工作。

【问题讨论】:

  • 哪条线段错误? std::max_element() 调用(如问题文本所示)或 *max 取消引用(如问题标题所示)? tempdata 是非空的吗?
  • 您是否在空向量上搜索最大元素?
  • @Angew 这是段错误的 *max 行。

标签: c++ c++11


【解决方案1】:

maxstd::end(tempdata) 时它将不起作用,如果您的tempdata 为空,则会发生这种情况。

迭代器到范围 [first, last) 中的最大元素。如果范围内的多个元素等价于最大元素,则将迭代器返回到第一个这样的元素。如果范围为空,则返回最后一个。

source

【讨论】:

  • 我发现数据没有正确写入临时数据,现在已经修复。谢谢。
猜你喜欢
  • 1970-01-01
  • 2013-11-10
  • 2015-08-07
  • 2016-03-04
  • 2013-06-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多