Hello I am new to the c++ and have a problem with a Unique Pointer of a Object as a Key of a Map.
std::map<std::unique_ptr<Person>,string,?> phonebookMap2;
sort(phonebookMap2.begin(),phonebookMap2.end(),sortfunction2);
but then ther is this issue:no match for 'operator-' (operand types are 'std::_Rb_tree_iterator<std::pair<const std::unique_ptr, std::__cxx11::basic_string > >' and 'std::_Rb_tree_iterator<std::pair<const std::unique_ptr, std::__cxx11::basic_string > >')
i have class looking like this:
#ifndef PERSON_H
#define PERSON_H
#include ..
class Person
{
private:
string m_firstName;
string m_lastName;
string m_address;
public:
Person();
Person(const string& firstName, const string& lastName,
const string& address);
string getFirstName() const;
string getLastName() const;
string getAddress() const;
};
bool operator<(const Person& left, const Person& right){
return left.getFirstName() < right.getFirstName();
};
#endif // PERSON_H
Main:
#include...
bool sortfunction2(const std::unique_ptr<Person> &x,
const std::unique_ptr<Person> &y) { return x->getFirstName() < y->getFirstName(); }
int main()
{
//Template missing
std::map<std::unique_ptr<Person>,string,?> phonebookMap2;
phonebookMap2.insert(make_pair(std::make_unique<Person>("Max", "Mustermann", "Bahnstr. 17"),"06151 123456"));
phonebookMap2.insert(make_pair(std::make_unique<Person>("Hubert", "Kah", "Minnesängergasse 23"),"06151 654321"));
//Not working
sort(phonebookMap2.begin(),phonebookMap2.end(),sortfunction2);<br />
You cannot std::sort
a std::map
. Elements in a std::map
are sorted and you cannot change order, that would break invariants of the map.
You can provide the comparison as functor. Then you only need to specify the functors type as argument of std::map
:
struct PersonCompare {
bool operator()(const std::unique_ptr<Person>& left, const std::unique_ptr<Person>& right) const {
return left->getFirstName() < right->getFirstName();
}
};
int main() {
//Template missing
std::map<std::unique_ptr<Person>,string,PersonCompare> phonebookMap2;
phonebookMap2.insert(make_pair(std::make_unique<Person>("Max", "Mustermann", "Bahnstr. 17"),"06151 123456"));
phonebookMap2.insert(make_pair(std::make_unique<Person>("Hubert", "Kah", "Minnesängergasse 23"),"06151 654321"));
}