views:

102

answers:

2

i have a 2-d vector like vector < vector < coordinates > > v( points); where coordinates class is:

class coordinate{
    public :
    int x;
    int y;
    coordinate(){
        x=0;
        y=0;
    }

};

and points is 20. how to sort the individual vectors v[i] based on v[i].size() , ie based on number of coordinates objects pushed in v[i]. ???

+8  A: 

1) make a function that compares two vectors based on size:

bool less_vectors(const vector& a,const vector& b) {
   return a.size() < b.size();
}

2) sort with it

sort(v.begin(),v.end(),less_vectors);
Will
You probably mean `return a.size() < b.size();`
visitor
@visitor: No he meand std::less http://www.sgi.com/tech/stl/less.html
Martin York
@Martin: Then it should be `std::less<size_t>()(a.size(), b.size())`. There's hardly any reason to use less here, seeing that all it does is wrap `operator<` to compare the values.
UncleBens
Are we arguing about style or correctness? I actually originally put in std::less because I anticipated that if I put in a simple < someone would ... complain in the comments that I wasn't drinking the stl kool aid ;)
Will
@Martin: Since when is `std::less` a function? Did you look at the reference you posted? - @Will: IMO the use of a function object is completely out of place here. If you were to add two integers, it wouldn't occur to you to go `int c = std::plus<int>()(a, b);`? ;) std::less has other purposes, e.g when you want to bind a constant to a predicate: `std::find_if(x, y, std::bind2nd(std::less<int>(), 0))` etc
UncleBens
Sorry. Misread the documentation.
Martin York
A: 
  1. make a function which you can use whatever attributes to compare the objects and then use STL sort() algorithm to sort the container.

  2. overload the < operation of that class and make it the same as the above function. Then you can use the sort() function provided by the STL containers (like STL list).

Foxcat