0

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.

2
  • 3
    The second type parameter to a set is the sorting algorithm that the set uses to organize itself, so if you were to try and convert a set to another type of set with a different sorting algorithm (the default in this case would be less<People>, i.e., person1 < person2), I wouldn't necessarily expect to get the same set - it would be sorted differently. Is that what you intend to do - you want the same set sorted in a different way?
    – Ben S.
    Commented Nov 10, 2017 at 0:27
  • Yes I have a default Sort in the person class that it will revert too. Commented Nov 10, 2017 at 0:33

2 Answers 2

4

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.

1

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;
}
3
  • @Yakk why is it not C++? Commented Nov 10, 2017 at 0:44
  • you have blended in a little c#
    – pm100
    Commented Nov 10, 2017 at 0:53
  • For the same reason "bonjour" is not English? Commented Nov 10, 2017 at 1:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.