为什么下面的代码给出'std :: logic_error'what:basic_string :: _ M_construct null无效?

问题描述

我得到std :: logic_error'what():basic_string :: _ M_construct null无效,当我使用for循环运行sort_string函数时,但不能使用简单的关系运算符来比较两个字符串。 该程序从给定数字的向量构造最大的数字。对于较小的输入,它可以正常工作,但对于较大的输入,则不能正常工作。我在下面提供了输入。

  getGenerationSpecies(index) {
    return this.http.get(`${this.baseUrl}/generation/${index}`).pipe(
      map((species) => {
        let pokemonSpecies = Object.keys(species["pokemon_species"]);
        species["id"] = pokemonSpecies
          .map((speciesKey) => species["pokemon_species"][speciesKey])
          .filter((id) => id);
        console.log("species:",species);
        return species;
      })
    );
  }

说明: 使用g ++ -std = c ++ 14

输入:

100

2 8 2 3 6 4 1 1 10 6 3 3 6 1 3 8 4 6 1 10 8 4 10 4 1 3 2 3 2 6 1 5 2 9 8 5 10 8 7 9 6 4 2 6 3 8 8 9 8 2 9 10 3 10 7 5 7 1 7 5 1 4 7 6 1 10 5 4 8 4 2 7 8 1 1 7 4 1 1 9 8 6 5 9 9 3 7 6 3 10 8 10 7 2 5 1 1 9 9 5

解决方法

通过将return true之外的for loop更改为return false,您的代码将可以正常工作。但是,我不明白为什么您会简单地将代码 SO 复杂化

bool sort_string(const std::string& x,const std::string& y)
{
  return x > y;
}

甚至将其实现为lambda。

,

问题是由

引起的
return true;
sort_string

。应该是

return false;

到达该行时,xyyx 相等。因此,yx < xyfalse,而不是true

return xy >= yx;

有效,因为该行与

相同
return yx < xy;