[Solved] How to sort the column of a 2d vector? [closed]


The issue is that for each iteration of the for loop, the std::sort can potentially change the already sorted column.

For example, if you sort column i, then columns i-1, i-2, etc. can lose the changes that were made to sort those columns.

Without changing too much of your original code, and albeit not the most efficient way to do this, you could create an auxiliary std::vector<std::vector<int>> and save the sorted column results of each iteration inside the loop in the auxiliary vector.

When done with the loop, assign the auxiliary vector back to the original vector.

#include <vector>
#include <algorithm>
#include <iostream>

std::vector<std::vector<int>> A = {{2, 3, 4}, {34, 3, 1}, {4, 54, 2}};

int main()
{
    if ( !A.empty() && !A[0].empty() )
    {
        auto auxV = A; // The auxiliary vector<vector>

        for (size_t i = 0; i < A[0].size(); i++)
        {
            // Sort column i
            std::sort(A.begin(), A.end(), [&](vector<int>& l, vector<int>& j) {
                return (l[i] < j[i]); 
                });

            // Save the results of the sort of column i in the auxiliary vector  
            for (size_t j = 0; j < A.size(); ++j)
                auxV[j][i] = A[j][i];
        }
        A = auxV; // copy the results back to the original vector
   }

    // display results
    for (auto& row : A)
    {
        for (auto el : row)
            std::cout << el << " ";
        std::cout << "\n";
    }
}

Output:

2 3 1 
4 3 2 
34 54 4 

solved How to sort the column of a 2d vector? [closed]