按第一列对多维矢量排序 [英] sort multidimensional vector by 1st column
问题描述
我想根据第一行中的数据快速对多维矢量进行排序.有多种方法可以做到(请参阅本帖的答案),但我在寻找以一种无需使用C ++ 11的快速有效的方式(即,对于所提供的第二种解决方案,我想避免创建和复制向量的成本).我试图查看
I want to quickly sort a multidimensional vector according to the data in the first row. There are ways to do this (see answers to this post) but I'm looking for a fast efficient way without using C++11 (i.e., for the 2nd solution provided, I would like to avoid the cost of creating and copying the vectors). I was trying to see if Boost had a nice sort feature like that of C++11 but am a novice at C++ and unable to figure it out. Essentially, I have data that looks like:
std::vector<std::vector<double> > data(2, std::vector<double>(5, 0.0));
data[0][0] = 2.0; data[1][0] = 4.0;
data[0][1] = 1.0; data[1][1] = 6.0;
data[0][2] = 3.0; data[1][2] = 5.0;
data[0][3] = 2.1; data[1][3] = 3.3;
data[0][4] = 0.3; data[1][4] = 5.7;
我想对数据进行排序,以便拥有
and I want to sort the data so that I have
data[0][0] = 0.3; data[1][0] = 5.7;
data[0][1] = 1.0; data[1][1] = 6.0;
data[0][2] = 2.0; data[1][2] = 4.0;
data[0][3] = 2.1; data[1][3] = 3.3;
data[0][4] = 3.0; data[1][4] = 5.0;
请注意,由于我事先不知道数据的尺寸,因此我正在使用矢量,但是数据将是矩形的,并且比此处提供的2x5示例大得多.
Note that I am using vectors since I do not know the dimensions of the data beforehand, however the data will be rectangular and much bigger than the 2x5 example provided here.
推荐答案
首先,声明一个函子:
struct FirstColumnOnlyCmp
{
bool operator()(const std::vector<double>& lhs,
const std::vector<double>& rhs) const
{
return lhs[0] < rhs[0];
}
};
然后,在您的std::sort
调用中使用它:
Then, use it in your std::sort
invoke:
std::sort(data.begin(), data.end(), FirstColumnOnlyCmp());
就是这样.不需要C ++ 11,它使事情变得容易得多,因为您可以使用lambda而不是函子来完成所有这些工作.
That's it. C++11 is not required, it just makes such things much much easier since you can do all this in a lambda rather than a functor.
我要确保所有data
集合中的向量都有至少一个元素以避免调用UB(我认为它们确实存在,否则,您的比较逻辑可能会变得更加复杂.
I leave it to you to ensure all vectors in the data
collection have at least one element to avoid invoking UB (I assume they do, otherwise your logic for comparison may need to get a little more complicated.
这篇关于按第一列对多维矢量排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!