hrk_er
hrk_er

Reputation: 73

custom comparator for pointers in a deque

I have a deque of pointers to a struct. I am trying to sort the deque with a comparator like the following:

struct timeCompE {
// ascending order by tt(unsigned long long), c(string), id(string)
bool operator() (const LogItem* a, const LogItem* b)const {
    if (a->tt == b->tt) {
        if (a->c == b->c) {
            return (a->id < b->id);
        } else {
            return (a->c < b->c);
        }
    } else {
        return (a->tt < b->tt);
    }
}};

however, the sort function doesn't seem to work the way I want it to:

std::sort(myDeque.begin(), myDeque.end(), timeCompE());

The code compiles, but the sort function doesn't work the way I want it to... I've tried looking for cases like this but couldn't find the exact. Also, am I able to pass in the const LogItem* by reference instead of value like i'm doing above? if so, what is the syntax for it? (I couldn't get that version to compile)

thank you in advance.

Upvotes: 0

Views: 957

Answers (1)

user4842163
user4842163

Reputation:

There's nothing wrong with the syntax/interface of your comparator provided that myDeque actually stores pointers to LogItem (deque<LogItem*> or deque<const LogItem*>).

Even the logic inside your comparator appears correct (slightly verbose but it should sort your elements in ascending order as desired).

If you're immediately segfaulting on executing the code, probably the problem is not with your comparator or even the sort but with respect to what you are storing inside the deque (ex: dangling pointers, nulls, pointers to data that was invalidated, etc).

Since it was requested, the signature for the comparator predicate if you want to compare references rather pointers would be:

bool operator() (const LogItem& a, const LogItem& b) const

However, that would only apply if you were storing LogItem objects and not pointers to them in the deque (deque<LogItem>, e.g., not deque<LogItem*>).

Upvotes: 1

Related Questions