I am trying to order a std::map, this map has an int as key and a class as a second element. This is the code:
#include <vector>
#include <algorithm>
#include <map>
class Position {
public:
bool operator < (const Position & pos) {
return x < pos.x;
}
bool operator > (const Position & pos) {
return x > pos.x;
}
int x;
int y;
};
class Element {
public:
bool operator < (const Element & pos) {
return position.x < pos.position.x;
}
bool operator > (const Element & pos) {
return position.x > pos.position.x;
}
int order;
Position position;
};
bool IsGreater(const std::pair<int, Element>& e1,const std::pair<int, Element>& e2) {
return e1.second.position.x > e2.second.position.x;
}
using namespace std;
int main()
{
std::map<int,Element> elements;
Element e1;
Element e2;
Element e3;
e1.position.x = 2;
e2.position.x = 1;
e3.position.x = 0;
elements.insert(std::pair<int, Element>(2, e1));
elements.insert(std::pair<int, Element>(1, e2));
elements.insert(std::pair<int, Element>(0, e3));
std::sort(elements.begin(), elements.end(), IsGreater);
for (unsigned int x = 0; x < elements.size(); x++) {
printf("Element %d order: %d\n", x, elements.at(x).order);
}
return 0;
}
Basically I have 2 class which are Position (contains an x and a y coordinate) and an Element (conains the index and the position). I need to order this map by the x coordinate in the position, but when I try to compile the code I have this 3 Issues:
Error C2676 binary '-': 'const std::_Tree_unchecked_iterator<std::_Tree_val<std::_Tree_simple_types<std::pair<const int,Element>>>>' does not define this operator or a conversion to a type acceptable to the predefined operator TestSort C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.25.28610\include\algorithm 3506
Error C2672 '_Sort_unchecked': no matching overloaded function found TestSort C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.25.28610\include\algorithm 3506
Error C2780 'void std::_Sort_unchecked(_RanIt,_RanIt,iterator_traits<_Iter>::difference_type,_Pr)': expects 4 arguments - 3 provided TestSort C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.25.28610\include\algorithm 3506
Initially I've tried to call std::sort with elements.begin() and elements.end(), no use, then I tried to include the operator oveload "<" and ">" on the element class... no luck, then I've tried to add the operator overload "<" and ">"... but again no luck! I've tried to use a lambda expression as third agrument of the sort method, nothing... and at the end I've tried to create a separate function for the sorting which returns a bool... but nothing worked. I simply cannot understand the problem and I cannot work out what's wrong. My question are: 1) What this error is telling me? 2) How can I solve it? Thanks in advance for any help!