【问题标题】:How to sort a vector of vectors while keeping the original indexes?如何在保留原始索引的同时对向量进行排序?
【发布时间】:2019-10-19 09:21:45
【问题描述】:

代码生成一个可变大小的矩阵,其列和行大小由用户定义。用户也手动填写第一行,然后自动填写其他行,第一行之后的每一行都是原始行除以我们所在的行。

现在我想在所述矩阵中找到N 最大的元素,其中N 是行数。当我打印包含N 最大值的数组/矩阵/向量时,在原始矩阵中元素的索引值旁边显示

对这个2D 向量进行排序,同时保留其原始索引的最佳方法是什么?

这对你们来说可能看起来很基础,但我已经为此苦苦挣扎了一段时间。

我已经尝试过排序功能,当我让它工作时,它会打乱索引并改变原始矩阵。

int main() 
{
    using namespace std;
    vector<string> header;
    vector<vector<double>> matrice;
    vector<double> temp;

    cout << "How many columns does it have?" << endl;
    cin >> columnsize;
    cout << "How many rows does it have?" << endl;
    cin >> rowsize;
    cout << "Whats the number of votos in order" << endl;
    for (int i = 0; i < columnsize; i++) 
    {
        cin >> ccontent;
        temp.push_back(ccontent);
    }
    matrice.push_back(temp);

    for (int i = 0; i < columnsize; i++) 
    {
        cout << "Qual é o nome da lista:" << i + 1 << endl;
        cin >> Nomelista;
        header.push_back(Nomelista);
    }

    for (int i = 1; i < rowsize; i++) 
    {
        temp.clear();
        for (int j = 0; j < columnsize; j++) 
        {
            temp.push_back((matrice[0][j]) / (i + 1));
        }
        matrice.push_back(temp);
    }
    return 0;
}

【问题讨论】:

  • “我尝试了排序功能,当我让它工作时,它会打乱索引并改变原始矩阵。”请显示该代码。您发布的代码似乎没有任何问题,但从您的文字来看,并不是 100% 清楚缺少什么/您想要做什么
  • @FilipeGomes 请按照建议添加minimal reproducible example。删去解决特定问题不需要的部分,但包含足以使其编译的部分。
  • 也许我不清楚你想要什么,但显而易见的答案似乎是复制原件,对副本进行排序,你就有了原件和副本。您也可以简单地将每行的最大值存储在一个单独的向量中(根据想要的顺序在排序之前或之后)
  • @DavidC.Rankin 这就是我一开始的理解。见我的first answer。后来OP在答案中发表了评论。他/她想按降序对矩阵中的所有元素进行排序,并且需要选择第一个N 元素及其对应的索引。其中N 是编号。矩阵的行数。

标签: c++ algorithm sorting multidimensional-array stdvector


【解决方案1】:

如果你的意思是

N = matrice.size() = no. rows of the matrix!

以下应该可以完成这项工作,即使这可能不是最好的方法。

  • 提供一个结构体ElementIntex,其中可以存储matrix元素及其对应的索引
  • 遍历matrix中的元素并将它们存储到ElementIntex的向量中。
  • 使用二元谓词根据结构ElementIntex 中的元素std::vector&lt;ElementIntex&gt; 进行排序。 (按降序排列)
  • 返回排序后的std::vector&lt;ElementIntex&gt; 中的第一个N 元素数,其中N 等于否。 matrix 中的行数。

以下是示例代码:(See Live)

#include <iostream>
#include <vector>
#include <cstddef>   // std::size_t
#include <algorithm> // std::sort

struct ElementIntex
{
    std::size_t col, row;
    double element;
    ElementIntex(std::size_t cl, std::size_t rw, double ele)
        : col{cl}
        , row{rw}
        , element{ele}
    {}
};

std::vector<ElementIntex> getLargestElements(
                          const std::vector<std::vector<double>>& matrice)
{
    std::vector<ElementIntex> vec;
    // reserve the memory to prevent unwanted reallocations: if you now the size
    // vec.reserve(/*total no. of elements*/)
    std::size_t rowIndex = 0;
    for (const std::vector<double>& row : matrice)
    {
        std::size_t colIndex = 0;
        for (const double element : row)
            vec.emplace_back(rowIndex, colIndex++, element);
        ++rowIndex;
    }
    // sort descending order of elements in the vector of `ElementIntex`
    std::sort(vec.begin(), vec.end(),
            [](const auto & lhs, const auto & rhs) { return lhs.element > rhs.element; });
    // return N largest elements from the sorted vector: where N = matrice.size() = no. rows!
    return { vec.cbegin(), vec.cbegin() + matrice.size() };
}

int main()
{
    // consider the following vector of vectors(matrx in your case)
    std::vector<std::vector<double>> matrice{
        {1.05, -8.05, 1.0, 8.58, 3.04},
        {15.05, 8.05, 7.05, 8.58},
        {11.05, 88.05, 7.06},
        {-12.05, -8.05}
    };

    const auto resultVec{ getLargestElements(matrice) };
    for (const ElementIntex& elementIndex : resultVec)
        std::cout << "The element " << elementIndex.element
                  << " and index [" << elementIndex.row 
                  << "][" << elementIndex.col << "]\n";

    return 0;
}

输出

The element 88.05 and index [1][2]
The element 15.05 and index [0][1]
The element 11.05 and index [0][2]
The element 8.58 and index [3][0]

【讨论】:

  • 嘿!非常感谢,我将如何修改它会给我整个矩阵的 N 个最大值,而不仅仅是每一行?我想在整个矩阵中找到最大值,N次,而那N次正好对应行数,所以我想找到最大值,然后是第二大的值,依此类推,N次,不是每行的最大值,这就是它的作用。
  • 我的意思是找到整个矩阵中的最大值,如果矩阵有 2 行,我想找到整个矩阵中的两个最大值,而不是每一行中的最大值。
  • 这正是我想要的!非常感谢!
【解决方案2】:
#include<bits/stdc++.h>
using namespace std;
int main()
{
    vector<vector<int>> v;
    int n;
    cin>>n;

    //input: 1 5 3 6 8 7 9
    // n =7
    for(int i=0; i<n; i++)
    {
    vector<int> temp1;
    int e;
    cin>>e;
    temp1.push_back(e);
    temp1.push_back(i);
    v.push_back(temp1);

    }

    sort(v.begin(),v.end());
    for(int i=0; i<n; i++)
    {
        cout<<v[i][0]<<" "<<v[i][1]<<endl;
    }

/* output: 
1 0
2 2
5 1
6 3
7 5
8 4
9 6*/
}

【讨论】:

  • #include&lt;bits/stdc++.h&gt;,真的吗?
  • 它不是标准的 C++ 头文件。为您使用的类/函数使用适当的头文件。
  • 嗯,你的回答应该可以为来这里的人提供与 OP 类似的问题。您的答案取决于某个开发环境,甚至可能取决于某个版本。你当然可以回答你想要的,但是通过将#include&lt;bits/stdc++.h&gt; 包含在建议的解决方案中来传播它是完全错误的。如果您完成这项工作并包含正确的文件(并且它回答了问题),您可能会获得赞成票。
  • 你可以使用任何你想要的东西。没有人编辑或删除您的答案。但是如果你选择使用不好的东西,当你被否决时不要感到惊讶。该标头不可移植,并且是一个坏习惯,已被证明很难从新程序员中消除。它坏的。
  • 除了显示代码的问题外,这个答案也不完整。请添加此代码如何解决问题的说明,或详细说明您所做的更改。
猜你喜欢
  • 2011-11-04
  • 2017-07-12
  • 1970-01-01
  • 1970-01-01
  • 2015-08-22
  • 1970-01-01
  • 1970-01-01
  • 2017-03-26
  • 1970-01-01
相关资源
最近更新 更多