【问题标题】:Segmentation fault using max_element() and min_element() in C++在 C++ 中使用 max_element() 和 min_element() 的分段错误
【发布时间】:2016-12-22 18:35:58
【问题描述】:

当我尝试运行此程序时,此部分会导致分段错误:

      std::vector<double> dist1(dist);

      dist1.erase(std::remove(dist1.begin(), dist1.end(), 0), dist1.end());

      max = *std::max_element(dist1.begin(),dist1.end());

      min = *std::min_element(dist1.begin(),dist1.end());

使用 max_element() 和 min_element() 会导致分段错误,但我不明白为什么。我在这里所做的是将向量“dist”复制到“dist1”,删除新向量中所有出现的“0”,然后从“dist”、“max”和“min”中的剩余项目中搜索最小值和最大值" 是先前声明的双精度类型变量。 "dist" 之前声明为

 std::vector<double> dist; //vector used to hold the distances between adjacent vertices

 dist.resize(size);

代码在 Linux 服务器上使用 g++ 编译。请指教。

【问题讨论】:

  • 如果每个编译成功的代码都自动没有错误,那我就失业了。

标签: c++ stl segmentation-fault std


【解决方案1】:

使用 max_element() 和 min_element() 会导致 分段错误,但我不明白为什么。

不,是结果的解引用导致了分段错误。

如果您在 empty 范围内使用这些函数,则返回结束迭代器。任何取消引用该迭代器的尝试都是未定义的行为。分段错误是未定义行为的一种典型但非必要的结果。

您必须防止向量为空(最好为此添加断言)或更改程序逻辑以支持空向量。

选项 1:

// code that prevents dist1 from being empty goes here
// ...
auto const max_iter = std::max_element(dist1.begin(), dist1.end());
assert(max_iter != dist1.end());
auto const max = *max_iter;

选项 2:

auto const max_iter = std::max_element(dist1.begin(), dist1.end());
if (max_iter == dist1.end())
{
    // do something to handle the special situation
}
else
{
    auto const max = *max_iter;
    // normal program flow
}

【讨论】:

    【解决方案2】:

    在应用 remove/erase 操作后,dist1 很可能是空的。

    如果输入区间为空std::min_elementstd::max_element,则返回输入范围的结尾。结果,您尝试取消引用 dist1.end() 并发生崩溃。

    【讨论】:

      【解决方案3】:

      我找到了一种让它工作的方法。而不是仅仅使用复制构造函数

      std::vector<double> dist1(dist)
      

      我还声明并调整了我的新向量,如下所示:

      std::vector<double> dist1(size);
      dist1=dist;
      

      还有一件事困扰着我:拷贝构造函数不应该完成所有这些吗?

      【讨论】:

        猜你喜欢
        • 2021-06-13
        • 2018-05-25
        • 2016-05-20
        • 1970-01-01
        • 2012-02-22
        • 2017-07-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多