dimanche 27 mai 2018

C++ sort coordinates stored as object in vector

In the next code I can input a number n then I can input n number of (x,y) coordinates.

Code:

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int n = 0;
char cr;
class punto{
private:
    int x;
    int y;
public:
    punto();
    ~punto(){}
    void setx(int xn){ x = xn;}
    void sety(int yn) { y = yn; }
    void printcoord();
};
punto::punto()
{
    x=0;
    y=0;
}
void punto:: printcoord()
{
    cout << x << " " << y << endl;
}
int main()
{
    vector<punto> list;
    int x;
        int y;
        punto *p1;
    cin >> n >> cr;
    for(int contador=0; contador<n; contador++){
        if(contador<n){
                cin >> x;
                cin >> y;
                p1=new punto;
                p1->setx(x);
                p1->sety(y);
                list.push_back(*p1);
                cin.get();
            }
        }
    vector<punto>::iterator it;
    if(cr=='x'){
     for ( it = list.begin(); it != list.end(); ++it ) {
            it->printcoord();
     }
    }
    if(cr=='y'){
     for ( it = list.begin(); it != list.end(); ++it ) {
            it->printcoord();
     }
    }
    return 0;
}

That means that if we input this:

5 x
1 2
3 4
6 1
2 2
1 1

We get this output.

1 2
3 4
6 1
2 2
1 1

Problem is I don't know how to sort coordinates with respect to x or y.

Coordinates are stored as objects within a vector.

If I try to use sort it says that x and y are non-class type int.

Output should be:

1 1                    1 1
1 2                    6 1 
2 2     for x          1 2          for y    
3 4                    2 2 
6 1                    3 4

I would appreciate any help.

Aucun commentaire:

Enregistrer un commentaire