Consider the following code. It is supposed to sort vector of vectors of ints in lexicographical order, i.e. by first column at first and then by second and so on. In my application I only care about first 6 out of 8 columns so was returning true in the case when values are equal for the first 6 columns.
And it caused problems (segmentation fault). It was working for 1000 data and it crashed for 1001. The example code is toy but sorting is a part of quite complicated program. I found out after long debugging that it was the cause of troubles. The program tries to sort array of all zeros with one (1, 0, ..., 0) entry.
Please any expert in C++, can you tell me what is wrong with the original (listed) program?
I was compiling it on 32bit and 64bit Linux and Visual Studio on 32bit Windows. It was always crashing. After the change in comment everything seems fine.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
const int COLS = 8;
bool compare (const vector<int>& r1, const vector<int>& r2)
{
for (int i = 0; i < COLS-2; i++)
if ( r1[ i ] != r2[ i ] )
return (r1[ i ] < r2[ i ]);
return true; //if true is replace by r1[ COLS-1 ] < r2[ COLS-1 ] then is OK
};
int main(int argc, char **argv)
{
int Na = 20;
vector< vector<int> > v( Na );
for (int r = 0; r < v.size(); r++)
v[r].resize(COLS, 0);
v[0][0] = 1;
cout << "Sorting\n";
sort( v.begin(), v.end(), compare );
cout << "Eof Sorting\n";
return 0;
}