通过常量id对自定义类型的向量进行排序 [英] Sorting vector of custom type by their constant id
问题描述
我需要排序一个自定义类型的向量 std :: vector< Blah> v
由Blah的整数ID。我通过 std :: sort(v.begin(),v.end())
使用运算符<
Blah
中重载
bool操作符< (const Blah& b)const {return(id< b.id); }
我注意到Blah的私有id不能被声明为 const int id
,否则类型 Blah
不满足 std :: sort
它与不是ValueSwappable冲突?)
如果 id
不是 const
一切都很好。但是,我不喜欢对象没有恒定的id只是为了重新排列它们在一个向量内的顺序的要求。
有没有办法,
有没有办法或是这样的方式?
我担心这是它的样子。如果你想对一个向量进行排序,这在原则上是一个数组,那么你必须在交换它们时分配。
这就是我想,实际上你可以骗了一点。将对象包装到联合中:
模板< typename T&
union ac {
//实际对象
T东西;
//赋值首先析构对象,然后复制
//构建一个新的inplace。
ac& operator =(ac< T> const& other){
thing。 〜T();
new(& thing)T(other。thing);
}
//需要提供构造函数,析构函数等
ac(T& t):thing(std :: forward< T& b {}
ac(ac< T> const& other):thing(other. thing){}
〜ac(){
〜T();
}
//如果你需要它们,添加移动赋值和构造函数
};然后,您可以实现(复制)赋值运算符,首先销毁当前对象,然后(复制)
您还需要提供构造函数和析构函数,当然这只适用于C ++ 11和更高版本
这似乎工作很不错:现场演示。
但是,我认为您应该首先重温一些设计选择,例如如果常量id真的需要是你的对象的一部分
I need to sort a vector of custom type std::vector<Blah> v
by Blah's integer id. I do this via std::sort(v.begin(), v.end())
with the operator <
being overloaded within Blah
as
bool operator< (const Blah& b) const { return (id < b.id); }
I noticed that Blah's private id cannot be declared as const int id
, otherwise the type Blah
does not meet the requirements for std::sort
(I assume it conflicts with not being ValueSwappable?)
If id
is not const
everything is fine. However, I dislike the idea of the objects not having constant ids just for the requirement of rearranging their order within a vector.
Is there a way around or is this the way it is?
解决方案
Is there a way around or is this the way it is?
I fear that this is the way it is. If you want to sort a vector, which is in principle an array, then you have to assign to elements when exchanging them.
At least that is what i thought, actually you can cheat a bit. Wrap your objects into an union:
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
};
You can then implement the (copy) assignment operator to first destruct the current object and then (copy) construct a new object from the provided inplace of the old object.
You also need to provide constructors and destructors, and of course this only works with C++11 and beyond due to limitations concerning the union members in previous language standards.
This seems to work quite nice: Live demo.
But still, I think you should first revisit some design choices, e.g. if the constant id really needs to be part of your objects
这篇关于通过常量id对自定义类型的向量进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!