sym*_*nic 7 c++ sorting vector
我需要std::vector<Blah> v通过Blah的整数id 对自定义类型的向量进行排序.我这样做是因为std::sort(v.begin(), v.end())操作员<在内部过载Blah
bool operator< (const Blah& b) const { return (id < b.id); }
Run Code Online (Sandbox Code Playgroud)
我注意到Blah的私有id不能被声明为const int id,否则该类型Blah不符合要求std::sort(我认为它与不是ValueSwappable冲突?)
如果id不是const一切都很好.但是,我不喜欢对象没有常数id的想法只是为了在向量中重新排列它们的顺序.
有办法还是这样?
有没有办法解决或者就是这样?
我担心事情就是这样。如果你想对一个向量(原则上是一个数组)进行排序,那么你必须在交换元素时对其进行赋值。
至少我是这么想的,实际上你可以作弊一点。将您的对象包装到一个联合中:
template<typename T>
union ac {
// actual object
T thing;
// assignment first destructs object, then copy
// constructs a new inplace.
ac & operator=(ac<T> const & other) {
thing. ~T();
new (& thing) T(other. thing);
}
// need to provide constructor, destructor, etc.
ac(T && t) : thing (std:: forward<T>(t))
{}
ac(ac<T> const & other) : thing (other. thing) {}
~ac() {
thing. ~T();
}
// if you need them, add move assignment and constructor
};
Run Code Online (Sandbox Code Playgroud)
然后,您可以实现(复制)赋值运算符以首先析构当前对象,然后(复制)从提供的旧对象位置构造一个新对象。
您还需要提供构造函数和析构函数,当然,由于以前的语言标准中有关联合成员的限制,这只适用于 C++11 及更高版本。
这似乎工作得很好:现场演示。
但我仍然认为你应该首先重新审视一些设计选择,例如,如果常量 id 确实需要成为你的对象的一部分