std::vector

HI,
I have a struct defined as

std::vector<pointt> arr;
struct pointt
{
pointt(double _x, double _y) : x(_x), y(_y) {}
bool operator < (const pointt &p) const {return (p.y < y);}
bool operator > (const pointt &p) const {return (p.y > y);}
double x, y;
};
I am adding values in arr.push_back
which is coming from some function at runtime

I am sort this see below

std::sort(arr.begin(), arr.end());
std::reverse(arr.begin(), arr.end());

my list now shows(in increasing order of values of y)
eg:
(27.98,9.045)
(26.98,9.045)
(27.51,9.045)
(16.14,22.14)



Now My requirement is like this
for the same value of y, I have to arrange x in increasing order
from above list I want
(26.98,9.045)
(27.51,9.045)
(27.98,9.045)
(16.14,22.14)
only for the same value of y, I have to arrange x in increasing order
Thanks
Operator< has exactly two possible answers: true and false.
In A < B the A either is "smaller" than B, or is not.

If A.y < B.y, then clearly A < B is true
Else If A.y > B.y, then clearly A < B is false
Else A.y == B.y and the result of A < B depends on the result of A.x < B.x

You simply have to expand the code in your operator to evaluate correctly.
Pretty much what kesiverto noted.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// Example program
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <ctime>

struct pointt
{
pointt(double _x, double _y) : x(_x), y(_y) {}
    bool operator < (const pointt &p) const {
        if (*this == p) {
            return x < p.x;
        }
        return y < p.y;
    }
    bool operator > (const pointt &p) const {
        if (*this == p) {
            return x > p.x;
        }
        return y > p.y;
    }
    bool operator==(const pointt& p) const {
        return (y == p.y);
    }
double x, y;
};

int main()
{
    srand(time(NULL));
    std::vector<pointt> results;
    
    for(int loop = 10; loop--; ) {
        results.push_back(pointt(rand() % 20, rand() % 20));
    }
    
    std::cout << "Before sort\n";
    for (const auto& val : results) {
        std::cout << val.x << '\t' << val.y << '\n';
    } 
    
    std::sort(results.begin(), results.end());
    std::cout << "After sort\n";
    for (const auto& val : results) {
        std::cout << val.x << '\t' << val.y << '\n';
    }
}
Thanks
Topic archived. No new replies allowed.