While solving a certain ds algo question,I had to sort the array using a custom comparator.I don't know why is it showing me errors at that particular line
Code
#include"bits/stdc++.h"
using namespace std;
struct train{
int platform,arrive,depart;
};
bool compare(train x,train y)
{
return x.depart<y.depart;
}
int maxTrains(vector<train> arr[])
{
int ans=0;
sort(arr,arr+arr.size(),compare);
return ans;
}
int main()
{
return 0;
}
Error message: no instance of overloaded function "sort" matches the argument list -- argument types are: (std::vector<train, std::allocator> *, , bool (train x, train y))[13,6]
{ "resource": "/F:/programming/dsa cracker sheet/maximum trains for which stoppage can be provided/max-trains.cpp", "owner": "C/C++", "code": "153", "severity": 8, "message": "expression must have class type but it has type "std::vector<train, std::allocator> *"", "source": "C/C++", "startLineNumber": 13, "startColumn": 19, "endLineNumber": 13, "endColumn": 22 }[13,19]
There are several things wrong. First, This line is really saying vector<train>* arr
, Pointer to a vector. But you used vector
so array and memory management is totally internal to it. And you are using sort
which is in-place sorting algorithms means, it modifies the original array, so you have to pass it via reference.
int maxTrains(vector<train> arr[])
This is the correct way.
int maxTrains(vector<train>& arr) //if you want modify original
Second, are you using sort which expects sort(Iterator begin, Iterator end, compare);
This is how you call std::sort
.
sort(arr.begin(), arr.end(),compare);
This is what you want, the rest works fine. I do not know what exactly you want to do with maxTrain
so I am just fixing the errors.
int maxTrains(vector<train>& arr)
{
int ans=0;
sort(arr.begin(), arr.end(),compare);
return ans;
}
Using these lines is a very bad practice.
#include"bits/stdc++.h"
using namespace std;
Try to be explicitly as much as you can, this way you can learn more.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments