为什么 std::sort 使用这个简单的严格弱排序比较仍然崩溃?

问题描述 投票:0回答:1

这是我的代码:

#include<vector>
#include<algorithm>
#include<iostream>
using namespace std;
void test()
{
    vector<vector<int>> info = {{0,0,999}, {0,1,1000}, {0,2,1001},
                {0,3,1002}, {0,4,1003}, {0,5,1004},
                {0,6,1005}, {0,7,1006}, {1,0,1000},
                {1,1,999}, {1,2,1000}, {1,3,1001},
                {1,4,1002}, {1,5,1003}, {1,6,1004},
                {1,7,1005}, {2,0,1001}, {2,1,1000},
                {2,2,999}, {2,3,1000}, {2,4,1001},
                {2,5,1002}, {2,6,1003}, {2,7,1004},
                {3,0,1002}, {3,1,1001}, {3,2,1000},
                {3,3,999}, {3,4,1000}, {3,5,1001},
                {3,6,1002}, {3,7,1003}, {4,0,1003},
                {4,1,1002}, {4,2,1001}, {4,3,1000},
                {4,4,999}, {4,5,1000}, {4,6,1001},
                {4,7,1002}, {5,0,1004}, {5,1,1003},
                {5,2,1002}, {5,3,1001}, {5,4,1000},
                {5,5,999}, {5,6,1000}, {5,7,1001},
                {6,0,1005}, {6,1,1004}, {6,2,1003},
                {6,3,1002}, {6,4,1001}, {6,5,1000},
                {6,6,999}, {6,7,1000}, {7,0,1006},
                {7,1,1005}, {7,2,1004}, {7,3,1003},
                {7,4,1002},{7,5,1001}};  
    auto cmp=[](const auto& a,const auto& b){
      if(a[2]<b[2])return true;
      if(a[0]<b[0])return true;
      return a[1]<b[1];       
 };

 sort(begin(info),end(info),cmp);

}
int main()
{
  test();
}

我使用g++ 13.2在Ubuntu 24.04 LTS(Linux 6.8.0-39-generic)下编译构建并运行代码在排序时崩溃,非常奇怪:

zzhao@zzhao-System-Version:~$ g++  -std=c++20 z3.cpp

zzhao@zzhao-System-Version:~$ ./a.out

Segmentation fault (core dumped)
c++ sorting
1个回答
0
投票

您的比较器不遵守严格弱顺序。

举个例子: a = {2,0,1}, b = {1,0,2}

对于比较器中的 aif,它将返回 true),对于其中的 bif 也返回 true)。

© www.soinside.com 2019 - 2024. All rights reserved.