tags:

views:

84

answers:

5

I have following code:

#include <vector>
using namespace std;
struct Point
{
  int x, y;
};
bool Sort(struct Point& a,struct  Point& b){
  return a.x<b.x;
}
int main(int argc, char *argv[])
{
  vector<Point>a;
  for (int i=0;i<10;i++){
    cin>>a[i].x>>a[i].y;
  }
  sort(a,10,Sort);
  system("PAUSE");
  return EXIT_SUCCESS;
}

but it seems wrong. Can you please tell me the correct form of the sort function to use?

+4  A: 

You should call it like that:

sort( a.begin(), a.end(), Sort);

http://www.cplusplus.com/reference/algorithm/sort/

Draco Ater
+1  A: 

I think it should be something like this:

static bool Sort(const Point& a, const Point& b) {
    return a.x<b.x;
}

Not quite. See comment.

tdammers
NM, the formatting suggested `Sort` were a method of Point.
tdammers
+3  A: 

You need to specify the start and end iterator for the sort function. This can be done by using a.begin() and a.end() functions.

std::sort( a.begin(), a.end(), Sort); 

Also, The predicate defn' should be:

bool Sort(const Point& a,const Point& b) const

{

aJ
rwong
@rwong: It was actually a global function, but the formatting was quite appalling and it looked like a class method. I've just fixed it.
Gorpik
A: 
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;

struct Point
{
  int x, y;
};

bool PCompare(const struct Point& a, const struct Point& b) {

    if(a.y < b.y)
        return true;
    if(a.y > b.y)
        return false;
    return a.x<b.x;
}

int main(int argc, char *argv[])
{
  vector<Point> a;
  for (int i=0;i<10;i++) {
      Point p ;
    cin>>p.x>>p.y;
    a.push_back(p);
  }

  sort(a.begin(), a.end(), PCompare);
  system("PAUSE");
  return EXIT_SUCCESS;
}
A: 

Another solution in your case is using list instead of vector and overloading operator <:

#include <iostream>
#include <algorithm>
#include <list>

struct Point
{
    int x, y;

    bool operator<( const Point & p )
    { return this->x < p.x; }
};

void print( Point p )
{
    std::cout << "Point (x,y): (" << p.x <<", " << p.y << ")" << std::endl;
}

// just for example
bool Reverse( const Point &p1, const Point &p2 )
{ return p1.x > p2.x; }

int main( )
{
    std::list<Point> a;

    for( int i = 0; i < 10; ++i) 
    {
        Point p;
        std::cin >> p.x >> p.y;
        a.push_back( p );
    }

    a.sort( );
    std::for_each( a.begin( ), a.end( ), print );

    std::cout << std::endl;

    a.sort( Reverse );
    std::for_each( a.begin( ), a.end( ), print );
}

std::list provides specialized algorithms unique to linked lists, such as splicing, sorting, and in-place reversal.

Bruno Caponi