简体   繁体   English

使用内置的C ++排序功能对2D数组进行排序

[英]Sorting a 2d array using built in c++ sort function

I was trying to sort an array of type int[1000][2] based on its first entry( int [i][0] ), and I used the sort function in the STL and wrote my own comparison object. 我试图根据其第一个条目( int [i][0] )对类型为int[1000][2]的数组进行排序,然后在STL中使用了sort函数并编写了自己的比较对象。 But when compiled it says that array type int[2] is not assignable. 但是在编译时会说数组类型int [2]是不可分配的。 What is the problem with my code? 我的代码有什么问题?

#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;
}

You can change your variable from 您可以从

int a[1000][2]

to a 到一个

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

or 要么

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

Then std::sort will just work as you intend since std::pair and std::array already have an operator< defined. 然后,因为std::pairstd::array已经定义了operator<所以std::sort将按预期工作。

What is the problem with my code? 我的代码有什么问题?

In fact c-style arrays cannot be assigned, and std::sort calls the assignment operation implicitly. 实际上,不能分配c样式的数组,并且std::sort隐式调用分配操作。 They need to be filled using std::copy or alike. 它们需要使用std::copy或类似方式填充。

I'd recommend you use a std::array<std::array<int,2>,1000> instead of the raw array. 我建议您使用std::array<std::array<int,2>,1000>而不是原始数组。

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

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