_mario.lat said:
I have a struct like that (for a graph):
struct edge {
int nodea;
int nodeb;
int weight;
}
I have an array of this struct:
struct e edge[250000000000];
How can I order this struct by the weight?
how can I use 'sort' function of std library?
Thankyou in advance, Mario.
First of all, I'd like to advise you to drop the array and use a
std::vector instead, unless you have a good reason to use an array.
Vectors are more user friendly.
Now, in order to sort your struct, you need a function that compares two
Edge objects. In the code below, the function a_less does this by
returning true if the first argument has a smaller 'a' than the second.
This function can also be made a static member function of Edge. For
convenience, i also added a constructor to your class.
The code sorts both an array and a std::vector.
have fun.
//---------------------------------------------------------------------------
#include <vector>
#include <algorithm>
struct Edge {
int a;
int b;
Edge(int a0, int b0): a(a0), b(b0){}
};
bool a_less(Edge & arg1, Edge & arg2 ){ return arg1.a < arg2.a; }
int main(int argc, char* argv[])
{
// sorting an std::vector
std::vector<Edge> v;
v.push_back( Edge(3,0) );
v.push_back( Edge(1,0) );
v.push_back( Edge(2,0) );
std::sort( v.begin(), v.end(), a_less );
// sorting an array
Edge array[3] = { Edge(3,0), Edge(1,0), Edge(2,0) };
std::sort( &array[0], &array[3], a_less );
return 0;
}
//---------------------------------------------------------------------------