0

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. But when compiled it says that array type int[2] is not assignable. 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;
}

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

or a std::array<int, 2>, which is the same and preserves the semantics.
That would be one of the solution, but I just want to know what is the problem with the code that causes the error? Thank you.
1

What is the problem with my code?

In fact c-style arrays cannot be assigned, and std::sort calls the assignment operation implicitly. They need to be filled using std::copy or alike.

I'd recommend you use a std::array<std::array<int,2>,1000> instead of the raw array.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.