使用 lambda 谓词对向量的排序向量因内存损坏而崩溃

sorting vector of pair using lambda predicate crashing with memory corruption

我正在尝试对向量对进行排序,但如果我提供 lambda,它就会崩溃。

#include <stdio.h>
#include <vector>
#include <math.h>
#include <iostream>
#include <algorithm>
using namespace std;
vector <int> 
findClosestElements (vector <int>&arr, int k, int x)
{
  vector <pair<int, int>>temp;
  int j = 0;
  for (const auto & i:arr)
  {
    temp.push_back (make_pair (abs (i - x), i));
    cout << temp[j].first << " " << temp[j].second << " " << j << endl;
    j++;
  }
  sort (temp.begin (), temp.end (),[&](const auto & a, const auto & b)
  {
    return (a.first < b.first ? true : (a.second < b.second));
  }
  );
  vector < int >ans;
  for (int i = 0; i < k; i++)
  {
    ans.push_back (temp[i].second);
    cout << ans[i] << endl;
  }
  sort (ans.begin (), ans.end ());
  return ans;
}

int
main ()
{
  vector <int>t =
    { 0, 1, 2, 2, 5, 5, 7, 9, 11, 11, 13, 16, 16, 17, 17, 17, 17, 20, 21, 21,
    22, 23, 25, 30, 30, 31, 32, 32, 32, 34, 34, 38, 38, 39, 39, 41, 41, 42,
      43, 44, 46, 47,
    48, 48, 48, 49, 50, 52, 54, 54, 57, 57, 58, 59, 59, 60, 61, 63, 63, 63,
      63, 64, 64, 64,
    67, 68, 71, 72, 72, 73, 75, 76, 76, 77, 78, 78, 79, 83, 83, 83, 83, 84,
      85, 86, 90, 91,
    92, 93, 93, 94, 96, 96, 96, 97, 98, 98, 98, 98, 98, 99
  };

  vector <int>v = findClosestElements (t, 94, 47);
  return 0;
}

如果我不提供 lambda,代码可以正常工作。 基本上崩溃:

sort (temp.begin (), temp.end (),[&](const auto & a, const auto & b)
  {
    return (a.first < b.first ? true : (a.second < b.second));
  }
  );

没有崩溃:

sort (temp.begin (), temp.end ());

崩溃:

*** Error in `./a.out': corrupted size vs. prev_size: 0x0000000001865db0 ***

您的 lambda 以错误的方式进行比较。您需要修复它以符合 strict weak ordering,例如仅在 a.first == b.first:

时返回 a.second < b.second
sort (temp.begin (), temp.end (),[&](const auto & a, const auto & b)
{
  return (a.first < b.first ? true : (a.first > b.first ? false : (a.second < b.second)));
}

另一方面,sort (temp.begin (), temp.end ()); 使用 std::pair's comparator 进行正确比较。