Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoiding Helper Functions for Doing Comparisons

Say I have a type with a member function:

class Thing {
    std::string m_name;
public:
    std::string & getName() {
        return m_name;
    }
};

And say I have a collection of that type:

std::vector<Thing> things;

And I want to keep the things in order by name. To do that, I use std::lower_bound to figure out where to put it:

bool thingLessThan(Thing const& thing, std::string const& name) {
    return thing.getName() < name;
}

void addThing(std::string const& name) {
    vector<Thing>::iterator position = lower_bound(
        things.begin(), things.end(),
        name,
       thingLessThan);
    if (position == things.end() || position->getName() != name) {
        position = things.insert(position, Thing());
        position->getName() = name;
    }
}

Is there a way to do the same thing as the thingLessThan function without actually creating a function, perhaps using std::mem_fun, std::less, etc?

like image 587
Travis Parks Avatar asked Jul 02 '26 00:07

Travis Parks


1 Answers

Other than a lambda you can simply define an operator< which adheres to strict weak ordering to allow a container of your object to be comparable by STL algorithms with the default predicate std::less

class whatever
{
public:
   bool operator<(const whatever& rhs) const { return x < rhs.x; }

private:
   int x;
};

std::vector<whatever> v;
std::sort(v.begin(), v.end());
like image 90
AJG85 Avatar answered Jul 03 '26 14:07

AJG85



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!