Reputation: 89
I'm working on a code that requires me to do the following, given two vectors:
arrival : 0 0 1 8 9 10 20 20 30 40 41 42 42 43 44
duration : 4 3 1 5 3 1 15 2 2 5 3 1 16 3 1
I'm trying to iterate over the vectors and when I find two or more consecutive elements, I need to sort them according to their duration in ascending order. So the output should be the following:
arrival : 0 0 1 8 9 10 20 20 30 40 41 42 42 43 44
duration : 3 4 1 5 3 1 2 15 2 5 3 1 16 3 1
As you can see, the duration for the first two 0's has been swapped. However, somehow it's swapping 16 with 1 for the arrival time 42
int p[pnum];
int temp;
for(int i=1;i<=pnum;i++){p[i] = i;}
for(int i=0;i<pnum;i++)
{
for(int j=0;j<pnum;j++)
{
if(arrival[i]<arrival[j])
{
temp=p[j];
p[j]=p[i];
p[i]=temp;
temp=arrival[j];
arrival[j]=arrival[i];
arrival[i]=temp;
temp=duration[j];
duration[j]=duration[i];
duration[i]=temp;
}
}
}
How can I fix this to get the right output? please help!
Upvotes: 0
Views: 124
Reputation: 14392
If you put arrival and duration in an std::pair<int,int>
and put that pair in a std::set
, they will be sorted as expected. If needed, you can make 2 new vectors with the sorted values.
A bit cleaner would be to use a struct with the needed fields, but then you should define a compare function to decide the order.
Upvotes: 1