【发布时间】:2021-05-22 12:16:53
【问题描述】:
在c++中,set可以自动对值进行排序,所以我只需要插入就行了。
对于自定义结构,我只需要定义运算符>和
#include <iostream>
#include <cmath>
#include <set>
using namespace std;
struct A {
A(int a) : a_(a) {}
friend bool operator <(const A& shot1, const A& shot2) {
return shot1.a_ < shot2.a_;
}
friend bool operator >(const A& shot1, const A& shot2) {
return shot1.a_ > shot2.a_;
}
int a_;
};
int main(int argc, char** argv) {
std::set<A> s;
A a1(10), a2(11), a3(9);
s.insert(a1);
s.insert(a2);
s.insert(a3);
for (auto i : s) {
cout << i.a_ << endl; // 9, 10, 11, it's sorted.
}
}
这可以工作,但是当我有一个自定义结构时,它很重,所以复制构造函数会很昂贵。我想像这样设置保存指针:
#include <iostream>
#include <cmath>
#include <set>
using namespace std;
struct A { // NOTICE HERE: A's contructor is very heavy
A(int a) : a_(a) {}
friend bool operator <(const A& shot1, const A& shot2) {
return shot1.a_ < shot2.a_;
}
friend bool operator >(const A& shot1, const A& shot2) {
return shot1.a_ > shot2.a_;
}
int a_;
};
int main(int argc, char** argv) {
std::set<A*> s;
A a1(10), a2(11), a3(9);
s.insert(&a1);
s.insert(&a2);
s.insert(&a3);
for (auto i : s) {
cout << i->a_ << endl; // 10, 11, 9, not sorted!!!!!!!
}
}
但是我认为设置排序功能失败了,那么,当设置值是指针时,我怎样才能让它工作呢?
【问题讨论】: