[英]Sorting a vector of objects with std::sort()
I have the following struct: 我有以下结构:
struct Invariant
{
public:
Invariant(int d, int dc)
: Dim(d), DimCoupl(dc) {}
void addTerm(int coeff, intVec pows)
{
Powers.push_back(pows);
Coefficients.push_back(coeff);
}
int Dim, DimCoupl;
std::vector<long> Coefficients;
std::vector<intVec> Powers;
};
Where IntVec
is a custom array of ints that's based on the arrays from the Boost library. 其中
IntVec
是一个基于Boost库中的数组的自定义int数组。
I have an stl Vector of these object, and I'd like to sort them by the amount of elements of their Coefficients vectors. 我有一个这个对象的stl Vector,我想根据它们的Coefficients矢量元素的数量对它们进行排序。 So I define:
所以我定义:
bool compInv(const Invariant &one, const Invariant &two)
{
return (one.Coefficients.size() < two.Coefficients.size());
}
And use std::sort()
or std::stable_sort()
to sort the Vector. 并使用
std::sort()
或std::stable_sort()
对Vector进行排序。 Checking afterwards, the Vector is sorted, but is seems like the content of std::vector<intVec>
Powers is changed. 之后检查,Vector被排序,但似乎更改了
std::vector<intVec>
Powers的内容。 Furthermore, std::sort()
and std::stable_sort()
seem to alter them in a different way. 此外,
std::sort()
和std::stable_sort()
似乎以不同的方式改变它们。 What could be causing this? 可能是什么导致了这个?
Edit: The definition of the IntVec: 编辑:IntVec的定义:
typedef blitz::Array<int,1> intVec;
Which I use because they are easier to initialize than regular arrays, which is very important since I have to create a lot of these objects that each contain a lot of these vectors. 我使用它是因为它们比常规数组更容易初始化,这非常重要,因为我必须创建很多这些对象,每个对象都包含很多这些向量。
Without a SSCCE it's hard to tell what is wrong with your code, but it looks like you're caught by using a class from an outdated library (blitz++), which seemed to have ceased further development/updating/debugging several years ago. 如果没有SSCCE,很难说你的代码出了什么问题,但看起来你已经被一个过时的库(blitz ++)中的一个类所困扰,这个类似乎已经在几年前停止了进一步的开发/更新/调试。
Since blitz::Array<int,1>
is a dynamically allocated 1D array of integers, there is no advantage over carefully using std::vector<int>
instead, when you get the full support (correct swap) and C++11 features (move semantics). 由于
blitz::Array<int,1>
是一个动态分配的1D整数数组,因此当你获得完全支持(正确的交换)和C ++ 11时,没有优势使用std::vector<int>
功能(移动语义)。 So, the first thing to try is 所以,首先要尝试的是
typedef std::vector<int> intVec;
and see if the symptoms persist. 并查看症状是否仍然存在。 If this involves too many changes to your code, try this first with a SSCCE (which initially must show the same symptoms as your code).
如果这涉及对代码进行太多更改,请首先使用SSCCE(最初必须显示与代码相同的症状)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.