簡體   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