简体   繁体   中英

How to convert set<obj, function> to set<obj>

I have a container class called people that stores a set of person objects. People takes in an std::function as one of set parameters. this is used to define a custom comparator to sort the set.

is it possible to covert from

set<Person, std::function<bool(const Person &p1, const Person &p2)>>

to

set<Person>

A simplified version of the class is below

class People
{   
public :
    People() : people(compareByName()) {}
    void addPerson(Person p);
    set<Person> getPeople();

private:
    using PeopleSet = set<Person, std::function<bool(const Person &p1, const Person &p2)>>; // std::function for comparator type
    PeopleSet people;
};

set<Person> People::getPeople()
{
    return People;//Error Here (No sutable user defined conversion)
}

I want get people to return a set<Person> but am unsure how.

The simplest way to do this is something like:

set<Person> People::getPeople()
{
    set<Person> reordered_set(original_set.begin(), original_set.end());
    return reordered_set;
}

In this case, you're creating an entirely new set<Person> by copying elements from the original set. I'm not sure whether you're okay with doing that copying or not.

Ok I just done it myself by creating a new set and adding everything in a for each loop.

set<Person> People::getPeople()
{
    set<Person> peeps;
    for (Person const &p : people)
    {
        peeps.insert(p);
    }
    return peeps;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM