gpt4 book ai didi

c++ - C++ 中的 HackerRank 大排序段错误

转载 作者:行者123 更新时间:2023-12-02 09:55:57 29 4
gpt4 key购买 nike

我有一个关于 HackerRank 的 BigSorting task 的问题。

我的代码成功运行除 3 之外的所有测试。(我在我的谷歌驱动器上找到了我的程序在名称 input03.txt、input04.txt 和 input05.txt 下无法运行的文件。这是驱动器的链接。) https://drive.google.com/drive/u/1/folders/1psno2RbeYXX5ohHjs5BWke6E-K2cJl-3

我的程序因“段错误”错误而崩溃。我已经坐了 2 个小时,无法理解错误是什么。这是我在 StackOverflow 上的第一个问题,所以如果我做错了什么,我马上道歉。

这是代码。

#include <vector>
#include <string>
#include <iostream>
#include <algorithm>

bool isShorter(const std::string& s1, const std::string& s2)
{
if (s1.size() != s2.size())
{
return s1.size() < s2.size();
}
else
{
for (int i = 0; i < s1.size(); ++i)
{
int x = s1[i] - '0';
int y = s2[i] - '0';
if (x != y)
{
return x < y;
}
}
}
return true;
}

std::vector<std::string> bigSorting(std::vector<std::string> unsorted)
{
std::sort(unsorted.begin(), unsorted.end(), isShorter);
return unsorted;
}

最佳答案

赋予 std::sort 的功能应该对迭代器范围内的元素进行严格的弱排序,请参见 std::sort , Compare requirementsstrict weak ordering on wikipedia .

您的 isShorter产生一个不严格的命令。特别是它不具有 isShorter(x, x) == false 的属性。为所有 x .

问题是你返回 true当您在顺序中找不到任何一个字符串在另一个之前或之后,但您应该返回 false .

该函数应该建模 < ,而不是 <= .

这是否是段错误的原因尚不清楚,因为您没有给出完整的代码示例,但违反了 std::sort需求确实会导致未定义的行为。

关于c++ - C++ 中的 HackerRank 大排序段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60108990/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com