使用C ++中的max_element()和min_element()进行分段错误

时间:2016-12-22 18:35:58

标签: c++ stl segmentation-fault std

当我尝试运行此程序时,会出现本节中出现的分段错误:

      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 ++编译。请指教。

3 个答案:

答案 0 :(得分:1)

应用删除/删除操作后, dist1 很可能为空。

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

答案 1 :(得分:1)

  

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

不,结果的解除引用会导致分段错误。

如果您使用具有范围的函数,则返回结束迭代器。任何取消引用迭代器的尝试都是未定义的行为。分段错误是未定义行为的一个典型但不必要的结果。

你必须要么阻止你的向量为空(理想情况下为它添加一个断言),要么改变程序逻辑以支持空向量。

选项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 :(得分:0)

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

std::vector<double> dist1(dist)

我还声明并调整了我的新矢量大小如下:

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

仍然困扰我的一件事:复制构造函数不应该完成所有这些吗?