这里是'point'的结构
struct point
{
double x;
double y;
};
这是产生错误的函数, 我使用 .find() 存在问题,如下图所示。 当我将鼠标悬停在错误上时,它说"在模板中:二进制表达式的操作数无效('常量点'和'常量点')">
bool isChecked(point left, point right, set<vector<point>>const& inSet)
{
// Check both possible arrangements of points
vector<point> tmp1 = {left, right};
vector<point> tmp2 = {right, left};
// .find() returns an iterator up to the element found
// If not found, return element after last, .end()
auto first = inSet.find(tmp1);
auto second = inSet.find(tmp2);
// Check if elements were checked already
if (first != inSet.end() || second != inSet.end())
return true;
return false;
}
这是编译器提供的错误:
C:/msys64/mingw64/include/c++/12.2.0/bits/predefined_ops.h:45:23: error: no match for 'operator<' (operand types are 'const point' and 'const point')
45 | { return *__it1 < *__it2; }
| ~~~~~~~^~~~~~~~
In file included from C:/msys64/mingw64/include/c++/12.2.0/string:47:
C:/msys64/mingw64/include/c++/12.2.0/bits/stl_iterator.h:1246:5: note: candidate: 'template<class _IteratorL, class _IteratorR, class _Container> bool __gnu_cxx::operator<(const __normal_iterator<_IteratorL, _Container>&, const __normal_iterator<_IteratorR, _Container>&)'
1246 | operator<(const __normal_iterator<_IteratorL, _Container>& __lhs,
| ^~~~~~~~
C:/msys64/mingw64/include/c++/12.2.0/bits/stl_iterator.h:1246:5: note: template argument deduction/substitution failed:
C:/msys64/mingw64/include/c++/12.2.0/bits/predefined_ops.h:45:23: note: 'const point' is not derived from 'const __gnu_cxx::__normal_iterator<_IteratorL, _Container>'
45 | { return *__it1 < *__it2; }
| ~~~~~~~^~~~~~~~
C:/msys64/mingw64/include/c++/12.2.0/bits/stl_iterator.h:1254:5: note: candidate: 'template<class _Iterator, class _Container> bool __gnu_cxx::operator<(const __normal_iterator<_Iterator, _Container>&, const __normal_iterator<_Iterator, _Container>&)'
1254 | operator<(const __normal_iterator<_Iterator, _Container>& __lhs,
| ^~~~~~~~
C:/msys64/mingw64/include/c++/12.2.0/bits/stl_iterator.h:1254:5: note: template argument deduction/substitution failed:
C:/msys64/mingw64/include/c++/12.2.0/bits/predefined_ops.h:45:23: note: 'const point' is not derived from 'const __gnu_cxx::__normal_iterator<_Iterator, _Container>'
45 | { return *__it1 < *__it2; }
| ~~~~~~~^~~~~~~~
ninja: build stopped: subcommand failed.
你需要把它添加到你的代码中:
bool operator<(const point& lhs, const point& rhs)
{
return lhs.x < rhs.x;
}
使<运算符重载。
然后你写你的函数,你可以这样写它:
bool isChecked(point left, point right, set<vector<point>> inSet)
{
// Check both possible arrangements of points
vector<point> tmp1 = {left, right};
vector<point> tmp2 = {right, left};
if (inSet.find(tmp1) != inSet.end() || inSet.find(tmp2) != inSet.end())
{
return true;
}
else
{
return false;
}
}
来自Yksisarvinen的评论:
而且不是因为
find
,std::set
要求它的元素能与<
相媲美。std::vector
可以与<
进行比较,当且仅当其元素也与<
进行比较。
以上面的注释作为参考,如果其他读者不清楚,解决方案是重载<
运算符函数。