gpt4 book ai didi

C++ 对 vector vector 中的多列进行排序

转载 作者:行者123 更新时间:2023-11-27 23:55:34 25 4
gpt4 key购买 nike

我正在尝试使用我的嵌套 vector 对多列进行排序,但我不确定如何实际操作。我在这里搜索了一堆帖子,但它们只显示了如何对最多两列进行排序,我知道对一列进行排序如下:

sort(myVector.begin(), myVector.end(), [](vector<int> const a, vector<int> const b){return a[0] < b[0];});

我有一个输入,用户可以在其中输入 vector 的大小并相应地生成它,我希望能够对输出中的每一列进行排序。

例如:

未分类

{3, 7, 2}

{9, 6, 8}

{5, 1, 4}

已排序

{3, 1, 2}

{5, 6, 4}

{9, 7, 8}

最佳答案

这是线性代数库中的经典之作:由于元素访问模式,给定矩阵的布局会对性能产生很大影响。

您面临完全相同的结果。显然,在您的情况下,每个 int vector 都是一行。您需要对列进行排序。你可以做的是转置技巧:

  1. 计算矩阵的转置
  2. 对转置的行进行排序
  3. 计算回这个排序矩阵的转置
  4. 利润

一些代码来说明这个想法:

std::vector<std::vector<int>> transpose(std::vector<std::vector<int>> const& input) {
// For simplicity, I assume input is well formed, i.e.:
// - All int vectors have the same size
// - input is non-empty.
std::vector<std::vector<int>> tr_input;
for(std::size_t i = 0; i < input.front().size(); ++i) {
std::vector<int> tmp;
for (auto& vec : input) {
tmp.push_back(vec.at(i));
}
tr_input.push_back(tmp);
}
return tr_input;
}

现在我们有了转置函数,我们可以实现算法了。

std::vector<std::vector<int>> input = { { 3, 7, 2 },
{ 9, 6, 8 },
{ 5, 1, 4 } };
auto tr = transpose(input);
for (auto& v : tr) {
std::sort(v.begin(), v.end());
}
auto sorted = transpose(tr);

结果可以在这个Live Demo上查看

关于C++ 对 vector vector 中的多列进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42827748/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com