lundi 27 septembre 2021

Segmentation fault when applying std::sort to a vector of vectors of integers

I am writing a struct for sorting generic data types allowing for multiple values of the same in each object to be sorted (e.g. sorting a vector of vectors of integers). The code below is a simplified example of the code I've written, with an example using ints and the inner vectors sized to 2.

// Sort object
template <class te_DataType, int te_mValue>
struct Sort_Data
{
  std::size_t iData;
  std::array<te_DataType, te_mValue> Values;
};

// Sort object comparator
template<class te_DataType, int te_mValue>
inline bool isLess_Sort_Data(const Sort_Data<te_DataType, te_mValue>& data0, const Sort_Data<te_DataType, te_mValue>& data1)
{
  FORDO(ivalue, te_mValue)
    if(data0.Values[ivalue] >= data1.Values[ivalue]) continue;
    else return true;

  return false;
}

// Sorting struct
template <class te_DataType, int te_mValue>
struct Sorter
{
  // List of sorting objects
  std::vector<Sort_Data<te_DataType, te_mValue> > SortDataList;

  // Constructor/Destructor
  Sorter(const size_t mdata) : SortDataList(mdata) {}
  ~Sorter() = default;

  // Method to sort the objects in SortDataList
  inline void DataSort()
  {
    std::sort(SortDataList.begin(), SortDataList.end(),
              [](const Sort_Data<te_DataType, te_mValue>& a, const Sort_Data<te_DataType, te_mValue>& b) -> bool
              {
                FORDO(ivalue, te_mValue)
                  if(a.Values[ivalue] >= b.Values[ivalue]) continue;
                  else return true;
                return false;
              });
  }
};

When I randomly initialise the entries in the vector of vectors of ints (sized to 1e3), I get segmentation fault (core dumped) when I call the DataSort() method. I have run my code through Valgrind as well, and while it definitely picks up errors, I cannot make sense of them. Can anyone give me some advice on this?

std::random_device randDevi;
std::mt19937 randomEngine(randDevi());
std::uniform_int_distribution<int> randGenerInt(0, 1e7);

// Load randomised data
int mData = 1e3;
Sorter<int, 2> sorter(mData);
for(int idata = 0; idata < mData; ++idata)
{
  sorter.SortDataList[idata].iData = idata;
  for(int ii = 0; ii < 2; ++ii) sorter.SortDataList[idata].Values[ii] = randGenerInt(randomEngine);
}

sorter.DataSort(); // Segmentation fault occurs here

Aucun commentaire:

Enregistrer un commentaire