繁体   English   中英

c ++将struct var添加到导致错误的变量集

[英]c++ adding struct var to set of vars causing error

我有一些非常简单的 C++ 代码,它们从结构定义中创建点并尝试将这些点添加到集合中。

#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);

   }
}

但是当我运行这段代码时,它会抛出一个很大的控制台错误:

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; }
                ~~~~^~~~~

我的代码中有一部分是我做错了吗? 我只是想要一种方法来跟踪列表中的多个点。

集合是有序的,所以元素需要一个排序函数。 你的点课没有这个。 添加一个合适的定义

bool operator<(const Point& a, const Point& b);

例如

bool operator<(const Point& a, const Point& b)
{
    return a.x < b.x || a.x == b.x && a.y < b.y;
}

但是无论您选择什么排序函数,它都必须定义严格的弱排序

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM