【问题标题】:Sorting a 2d array using built in c++ sort function使用内置的 C++ 排序函数对二维数组进行排序
【发布时间】:2016-07-11 16:46:01
【问题描述】:

我试图根据第一个条目 (int [i][0]) 对 int[1000][2] 类型的数组进行排序,我使用了 STL 中的排序函数并编写了自己的比较对象。但是在编译时它说数组类型 int[2] 是不可分配的。我的代码有什么问题?

#include<iostream>
#include<fstream>
#include<algorithm>
class op {
public:
    bool operator()(int a[2], int b[2]) {
        return a[0] < b[0];
    }
};
using namespace std;
int main() {
    int money = 0;
    int a[1000][2] = { 0 };
    int total = 0, n = 0;
    cin >> total>>n;
    for (int i = 0; i < n; i++) {
        cin >> a[i][0] >> a[i][1];
    }
    sort(a, a + n - 1, op());//where the problem occurred

    for (int i=0; i<n; i++) {
        if (a[1][i] < total) {
            money = money + a[i][1] * a[i][0];
            total = total - a[i][1];
        }
        else {
            money = money + a[i][0] *total;
            break;

        }
    }
    cout << money << endl;

    return 0;
}

【问题讨论】:

    标签: c++ arrays sorting stl


    【解决方案1】:

    你可以改变你的变量

    int a[1000][2]
    

    到一个

    std::array<std::pair<int, int>, 1000>
    

    std::array<std::array<int, 2>, 1000>
    

    然后std::sort 将按您的意愿工作,因为std::pairstd::array 已经定义了operator&lt;

    【讨论】:

    • std::array&lt;int, 2&gt;,相同且保留语义。
    • 这将是解决方案之一,但我只想知道导致错误的代码有什么问题?谢谢。
    【解决方案2】:

    我的代码有什么问题?

    实际上c风格的数组是不能赋值的,std::sort隐式调用赋值操作。它们需要使用std::copy 或类似名称填写。

    我建议您使用 std::array&lt;std::array&lt;int,2&gt;,1000&gt; 而不是原始数组。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-10
      • 2015-09-17
      • 1970-01-01
      相关资源
      最近更新 更多