Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
676 views
in Technique[技术] by (71.8m points)

c++ - Ordered sort in STL containers

Sorry if the question title terminology is wrong, but here is what I want to do.I need to sort a vector of objects, but contrary to a typical comparison "less than" approach I need to re-position the objects based on some string ID property so that each same type members are positioned in consecutive order like this:

[id_town,id_country,id_planet,id_planet,id_town,id_country]

becomes this:

[id_town,id_town,id_country,id_country,id_planet,id_planet]

id_ property is string.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

std::sort has a third parameter which can be used to pass a boolean predicate that acts as custom comparator. Write your own comparator acording to your specifications and use it.

For example:

struct foo
{
    std::string id;

    foo(const std::string& _id) : id( _id ) {}
};

//Functor to compare foo instances:
struct foo_comparator
{
    operator bool(const foo& lhs , const foo& rhs) const
    {
        return lhs.id < rhs.id;
    }
};

int main()
{
    std::vector<foo> v;

    std::sort( std::begin(v) , std::end(v) , foo_comparator );
}

Also, in C++11 you could use a lambda:

std::sort( std::begin(v) , std::end(v) , [](const foo& lhs , const foo& rhs) { return lhs.id < rhs.id; } );

Finally, you can also overload the comparison operators (operator> and operator<) and use comparators provided by the standard library like std::greater:

struct foo
{
    std::string id;

    foo(const std::string& _id) : id( _id ) {}

    friend bool operator<(const foo& lhs , const foo& rhs)
    {
        return lhs.id < rhs.id;
    }

    friend bool operator>(const foo& lhs , const foo& rhs)
    {
        return rhs < lhs;
    }

    friend bool operator>=(const foo& lhs , const foo& rhs)
    {
        return !(lhs < rhs);
    }

    friend bool operator<=(const foo& lhs , const foo& rhs)
    {
        return !(lhs > rhs);
    }
};


int main()
{
    std::vector<foo> v;

    std::sort( std::begin(v) , std::end(v) , std::greater );
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...