Rahul Narayanan Rahul Narayanan - 1 year ago 90
C++ Question

How can I sort elements of a vector by row using std::sort

I want to sort the elements of a vector by row with the size of each row being different, for example if I have a

vector v = {
{5, 3, 1, 2},
{10, 1},
{3, 2, 1},
{4, 3, 2, 0}
}


final vector = { {1, 2, 3, 5},
{1, 10},
{1, 2, 3},
{0, 2, 3, 4}
}


How can I do this using std::sort function?

This is what I have tried so far.

vector< vector<int> > v;
for(int i = 0; i < n; i++){
sort(&v[i][i], &v[i][i] + n*m, less<int>());
}

Answer Source

You should be using a std::vector<std::vector<int>> to hold your data. Let's assume this change has been made.

Your ultimate goal is to sort each vector in your outer vector. This is perfectly easy with std::sort.

If you'd like to do it in-place, just call sort on each vector in the vector within a for-loop.

std::vector<std::vector<int>> vs = { 
    {5, 3, 1, 2},
    {10, 1},
    {3, 2, 1},
    {4, 3, 2, 0}
};

for(auto& v: vs) {
    std::sort(v.begin(), v.end());
}

Ideone it.

Similarly, but much less readable, is the use of std::for_each to apply std::sort to each element in the outer vector.

The ideone is included for this approach, but I'd caution to use the less verbose and more readable version above.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download