namu
namu

Reputation: 201

sort multidimensional vector by 1st column

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;

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.

Upvotes: 0

Views: 4691

Answers (1)

WhozCraig
WhozCraig

Reputation: 66204

First, declare a functor:

struct FirstColumnOnlyCmp
{
    bool operator()(const std::vector<double>& lhs,
                    const std::vector<double>& rhs) const
    {
        return lhs[0] < rhs[0];
    }
};

Then, use it in your std::sort invoke:

std::sort(data.begin(), data.end(), FirstColumnOnlyCmp());

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.

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.

Upvotes: 4

Related Questions