I was given 2 vectors:
vector<int> arrive;
vector<int> depart;
arrive[i] and depart[i] represent the arrival and departure times for different people. My task was to find that at any point of time the no of people should not exceed K(given).
For this I made a vector<pair<int,int>> arr_dep_time
. This array stored all the points of both arrival and departure arrays. pair.first was to store the time of arrival/departure and pair.second was to store if it is arrival pt(ie 0) or departure pt(ie 1).
then I used std::sort(arr_dep_time.begin(),arr_dep_time.end(),comparator)
I wanted that if I have duplicate times, it should place departure time first. For example, if {5,0} and {5,1} are there,then {5,1} should be placed before {5,0}. So, I wrote comparator as follows:
bool comparator(pair<int,int> p1,pair<int,int> p2){
if(p1.first==p2.first)
return p1.second>p2.second;
return p1.first<p2.first;
}
But this gave me wrong result on some cases. However, when I took pair.second as 0:departure 1:arrival and wrote comapartor as follows, it gave me correct result.
bool comparator(pair<int,int> p1,pair<int,int> p2){
if(p1.first==p2.first)
return p1.second<p2.second;
return p1.first<p2.first;
}
can anyone tell me why?
I have not included the complete solution.Just the part that I felt was necessary.
Since you're using c++14, perhaps you could use a lambda?
std::sort(arr_dep_time.begin(), arr_dep_time.end(), [] (auto &p1, auto &p2){
return (p1.first==p2.first) ? p1.second < p2.second : p1.first < p2.first;
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.