behemoth
behemoth

Reputation: 23

std::set< struct > sorted by property value in struct c++

I have this struct:

struct abc {
    int x, y;
    char s[20];
};

bool comp(abc a, abc b) {
    int n = strlen(a.s), m = strlen(b.s);
    for(int i = 0; i < min(n,m); i++)
        if(a.s[i] != b.s[i])
            return a.s[i] < b.s[i];
    return n < m;
}

I want to make a set with this structs sorted by s[] , but I don't know how.

Upvotes: 1

Views: 3978

Answers (2)

Gabriel
Gabriel

Reputation: 3584

You need to define the < operator for abc so that stl knows how to compare two instances of abc. So how do you compare two members of a struct that have 3 fields? Use lexicographical order.

Here is the practical implementation of your example.

struct abc {
    int x, y;
    char s[20];

   const bool operator < ( const abc &r ) const{
        return ( x< r.x)
               ||(( x== r.x) && ( y< r.y))
               ||(( x== r.x) && ( y== r.y) && strcmp(s,r.s)<0) ;
    }
};

Then the set is automatically sorted when you insert in it.

Upvotes: 2

Mike Seymour
Mike Seymour

Reputation: 254431

One option is to overload operator< for your structure. Any standard algorithm/container that wants to compare their sort order will use that by default.

bool operator<(abc const & a, abc const & b) {
    // your code here
}

Alternatively, you can specify your comparator just for the set:

std::set<abc, bool(*)(abc,abc)> my_set(comp);

This would be a bit more convenient with a function class rather than a function:

struct comp {
    bool operator()(abc const & a, abc const & b) {
        // your code here
    }
};

std::set<abc, comp> my_set;

Upvotes: 3

Related Questions