Writing a program that should be portable in Linux and Windows enviroments I have found a issue with the STL sort function, when compiling with Visual studio and gcc.
In order to sort a vector of complex data structures I have written an int conversion operator for the structures in that form:
struct result
{
public :
int Gene_a;
int Gene_b;
std::vector<int> score;
float total_score;
operator int() {return total_score;}
}
In that case I have no problem in visual studio using the standard sort algorithm for integers:
sort(results.rbegin(),results.rend());
But when trying to compile that using GCC ( actually g++ ) that lead to funny errors.
To avoid that seems that I have to write an ordering function:
inline bool better (result a, result b)
{
return a.total_score > b.total_score;
}
and invoke sort in the form:
sort(results.begin(),results.end(),better);
Was I using something out of the standard C++ or is a lack of the g++ STL implementation ?
Is it possible to let g++ understand that the vector of struct is equivalent to a vector of int ?
Here is a short main to illustrate the error:
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
int main(int argc, char* argv[])
{
vector<result> r; // define a vector of struct
for (int i=0;i<10;i++) // fill up with data
{
result a;
a.Gene_a=i;
a.Gene_b=2*i;
for(int j=0;j<i;j++)
a.score.push_back(i); // fill the int vector in the struct
a.total_score=i;
r.push_back(a);
}
// sort(r.rbegin(),r.rend()); // this line will fail in g++
sort(r.rbegin(),r.rend(),better);
for (int i=0;i<10;i++) // demonstrate that the int operator works
cout << (int)r[i] << endl;
}// End main
The only meaningful difference I see between the two comparison methods is that the second will work when the element is
const. The first should probably be:Even though you’re modifying the container, your comparison still has the requirement that it work on
constobjects. In your case, the implementation used that assumption and the error arose.But this shouldn’t matter, since to sort the container and its elements needs to be modifiable…