gpt4 book ai didi

c++ - 如何在 C++ 集合中插入值

转载 作者:太空宇宙 更新时间:2023-11-04 14:42:32 25 4
gpt4 key购买 nike

我正在尝试创建一组 Point 类的自定义对象

点.h

#ifndef POINT_H
#define POINT_H

class Point
{
float x_coordinate,y_coordinate;
public:
Point(float x, float y):x_coordinate(x),y_coordinate(y)
{}

float get_x()
{
return x_coordinate;
}

float get_y()
{
return y_coordinate;
}

bool operator==(Point rhs)
{
if( ((int)x_coordinate == (int)rhs.get_x()) && ((int)y_coordinate == (int)rhs.get_y()) )
return true;
else return false;
}

bool operator<(Point rhs)
{
if((int)x_coordinate < (int)rhs.get_x())
return true;
else return false;
}
};

#endif

刚开始写驱动

#include<iostream>
#include<set>
#include "point.h"
using namespace std;



int main()
{
Point p1(-10,-10),p2(-10,10),p3(10,10),p4(10,-10);
set<Point> points_set = set<Point>();
points_set.insert(p1);

return 0;
}

但是我在编译期间遇到了这个错误,我已经重载了比较和相等运算符,我还必须做什么才能让它工作?

In file included from /usr/include/c++/4.6/string:50:0,
from /usr/include/c++/4.6/bits/locale_classes.h:42,
from /usr/include/c++/4.6/bits/ios_base.h:43,
from /usr/include/c++/4.6/ios:43,
from /usr/include/c++/4.6/ostream:40,
from /usr/include/c++/4.6/iostream:40,
from driver.cpp:1:
/usr/include/c++/4.6/bits/stl_function.h: In member function ‘bool std::less<_Tp>::operator()(const _Tp&, const _Tp&) const [with _Tp = Point]’:
/usr/include/c++/4.6/bits/stl_tree.h:1267:4: instantiated from ‘std::pair<std::_Rb_tree_iterator<_Val>, bool> std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::_M_insert_unique(const _Val&) [with _Key = Point, _Val = Point, _KeyOfValue = std::_Identity<Point>, _Compare = std::less<Point>, _Alloc = std::allocator<Point>]’
/usr/include/c++/4.6/bits/stl_set.h:410:29: instantiated from ‘std::pair<typename std::_Rb_tree<_Key, _Key, std::_Identity<_Key>, _Compare, typename _Alloc::rebind<_Key>::other>::const_iterator, bool> std::set<_Key, _Compare, _Alloc>::insert(const value_type&) [with _Key = Point, _Compare = std::less<Point>, _Alloc = std::allocator<Point>, typename std::_Rb_tree<_Key, _Key, std::_Identity<_Key>, _Compare, typename _Alloc::rebind<_Key>::other>::const_iterator = std::_Rb_tree_const_iterator<Point>, std::set<_Key, _Compare, _Alloc>::value_type = Point]’
driver.cpp:12:25: instantiated from here
/usr/include/c++/4.6/bits/stl_function.h:236:22: error: passing ‘const Point’ as ‘this’ argument of ‘bool Point::operator<(Point)’ discards qualifiers [-fpermissive]

最佳答案

float get_x() const { ... }
float get_y() const { ... }
bool operator==(Point const& rhs) const { ... }
bool operator<(Point const& rhs) const { ... }

你错过了所有这些 const s,在参数和方法本身。

注意:我不确定 operator< 的要求是什么用于 set 中的项目, 但你提供的那个很弱。

关于c++ - 如何在 C++ 集合中插入值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7705747/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com