#53849: 想詢問c++ STL sort 自訂排序的問題


pofly (不挖鼻孔有害身心健康)


我寫的 struct 物件是長這樣

struct StudentInfo
{
  std::string name;
  int classroom;
  int id;
  std::string intro;
};

 

然後直接用 STL 的 sort 自訂排序,邏輯我這樣寫

bool Comp(const StudentInfo &a, const StudentInfo &b)
{
  if (a.classroom != b.classroom)
  {
      return a.classroom < b.classroom;
  }
  else if (a.id != b.id)
  {
      return a.id < b.id;
  }
  else if (a.name != b.name)
  {
      return a.name < b.name;
  }
  else
  {
      return a.intro < b.intro;
  }
}

 

結果就是各種 WA 和 SIGSEGV(疑似爆記憶體?)

像這樣的排序是不正確的嗎?

SIGSEGV 又是怎麼回是?

 

後來改寫成這樣,不再比較所有成員,只比較兩個 int 型態的成員,就 AC 了,但我不懂為什麼改成這樣就會 AC

bool Comp(const StudentInfo &a, const StudentInfo &b)
{
  if (a.classroom != b.classroom)
  {
      return a.classroom < b.classroom;
  }
  else
  {
      return a.id < b.id;
  }
}

 

如果是排序邏輯有誤,為什麼四個成員都比較得到的不是 WA,而是 SIGSEGV ?

 

又為什麼在 c++ 中四個都比較會得到錯誤答案? 而在 python 中四個都比較卻不會產生這樣的結果?

我用 python 寫的版本: github

(對,我本質上就只是把這段 python 程式碼改寫成 c++ 版的而已)