我创建了一个类似于下面这样的类"firefly“:
class firefly{
private:
float time_flash;
public:
firefly(int, int, float, float);//parametric constr.
firefly();
firefly(const firefly& a);//copy constructor
void receive_flash(std :: vector<firefly>&, float, float, int);
friend bool operator <(const firefly&) const;
};关注后两个函数;我有两个关于它们的问题。在主程序中,我想初始化萤火虫的向量,如下所示:
vector <firefly> fire_vec(10, firefly(5, 5,(float) 1., (float)1.) );使用参数化构造函数。我能这么做吗?第二个问题。该向量应该通过算法排序来排序,
sort(fire_vec.begin(), fire_vec.end());重载operator<如下:
bool operator <(const firefly &rhs) const {return time_flash < rhs.time_flash;} 这样做有什么错吗?(我觉得有问题,因为我做不到)
发布于 2012-01-07 22:32:06
我不知道您遇到了什么问题,但是如果您尝试编译这段代码,您会发现
friend bool operator <(const firefly&) const;是非法的:不能在独立函数上使用const限定符。此外,operator<是一个二元运算符,因此它应该接受两个类型均为const firefly &的参数。
您也可以按照自己的建议将operator<实现为成员函数,但随后删除friend声明。
除此之外,您的代码没有任何问题,只是可能对完全相等的元素的向量进行排序是浪费时间。
发布于 2012-01-07 23:49:18
对不起,您为什么选择vector+customized排序,而不是使用自定义比较器设置/映射?
通常,我们使用向量主要是因为需要通过索引随机访问它的元素。如果不是这样,特别是在您的情况下,您需要一个排序的向量,我建议使用set/map。
发布于 2012-01-07 23:54:04
对于第二个问题,您必须传递重载函数以作为参数进行排序
sort (myvector.begin()+4,myvector.end(),myfunction);
https://stackoverflow.com/questions/8770383
复制相似问题