繁体   English   中英

在C++中按列对二维数组进行排序

[英]sorting a 2d array by column in C++

我需要按列对二维数组进行排序。

10 20 5
15 13 43
0  14 1

我想将上面的数组转换成这样:

15 20 43
10 14 5
0  13 1

这是一个函数,它将int的二维数组作为标准容器std::array<std::array<int>>std::vector<std::vector<int>>并通过制作一个对每一列进行排序列的临时std::vector<int>并在其上使用std::sort

template<typename ArrayType>
void sortAllColumns(ArrayType& array) {
    // go through each column
    const size_t columns = array[0].size();
    for (size_t column_index = 0; column_index < columns; ++column_index) {
        // create a vector from column
        std::vector<int> column;
        column.resize(array.size());
        // add elements to column vector
        for (size_t row_index = 0; row_index < array.size(); ++row_index) {
            column[row_index] = array[row_index][column_index];
        }
        // sort column
        std::sort(column.begin(), column.end(), [](const int lhs, const int rhs) {
            return lhs > rhs;
        });
        // update column in array
        for (size_t row_index = 0; row_index < array.size(); ++row_index) {
            array[row_index][column_index] = column[row_index];
        }
    }
}

用法示例:

template <typename ArrayType>
void coutArray(const ArrayType& array) {
    for (const auto& row : array) {
        for (const auto& element : row) {
            std::cout << element << ' ';
        }
        std::cout << std::endl;
    }
}

int main() {
    std::vector array {
        std::vector{ 10, 20, 5 },
        std::vector{ 15, 13, 43 },
        std::vector{ 0, 14, 1 }
    };

    sortAllColumns(array);
    coutArray(array);
}

产生:

15 20 43
10 14 5
0 13 1

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM