Reputation: 1548
I have some pretty simple C++ code that creates points from a struct definition and tries to add those points to a set.
#include <stdio.h> /* printf */
#include <bits/stdc++.h> /* vector of strings */
using namespace std;
struct point
{
int x;
int y;
};
int main(){
for(int i = 0; i <= 6; i++){
set<point> visited_points;
point visited_point{4, 1};
visited_points.insert(visited_point);
}
}
But this code throws a large console error when I run it saying:
In file included from /usr/include/c++/7/string:48:0,
from /usr/include/c++/7/bits/locale_classes.h:40,
from /usr/include/c++/7/bits/ios_base.h:41,
from /usr/include/c++/7/ios:42,
from /usr/include/c++/7/istream:38,
from /usr/include/c++/7/sstream:38,
from /usr/include/c++/7/complex:45,
from /usr/include/c++/7/ccomplex:39,
from /usr/include/x86_64-linux-gnu/c++/7/bits/stdc++.h:52,
from ex.cpp:2:
/usr/include/c++/7/bits/stl_function.h: In instantiation of ‘constexpr bool std::less<_Tp>::operator()(const _Tp&, const _Tp&) const [with _Tp = point]’:
/usr/include/c++/7/bits/stl_tree.h:2038:11: required from ‘std::pair<std::_Rb_tree_node_base*, std::
........
/usr/include/c++/7/bits/stl_function.h:386:20: note: ‘const point’ is not derived from ‘const std::__cxx11::sub_match<_BiIter>’
{ return __x < __y; }
~~~~^~~~~
Is there a part of my code that I did wrong? I just want a way to keep track of multiple points in a list.
Upvotes: 0
Views: 47
Reputation: 87959
Sets are ordered, and so the elements need an ordering function. Your point class doesn't not have this. Add a suitable definition of
bool operator<(const Point& a, const Point& b);
For instance
bool operator<(const Point& a, const Point& b)
{
return a.x < b.x || a.x == b.x && a.y < b.y;
}
But whatever ordering function you choose it must define a strict weak ordering
Upvotes: 4