sort function is giving unexpected results
i have structure data as :
1 2 3 4
|
typedef struct
{
int num,index;
}data;
|
and my sort function as :
1 2 3 4
|
bool comp(const data &i , const data &j)
{
return (i.num < j.num);
}
|
and here is my main function :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
|
int t,n,p,tcase,i,j;
vector<data> a;
vector<int > b ;
cin >> n;
a.resize(n);
b.resize(n);
j=0;
for(i=0 ; i<2*n ; i++)
{
if(i%2)
{
b.emplace_back();
cin >> b[j];
j++;
}
else
{
a.emplace_back();
cin >> a[j].num;
a[j].index = j;
}
}
for(i=0 ; i<n ; i++)
{
cout << a[i].num << endl;
}
cout << endl;
sort(a.begin() , a.end() , comp);
for(i=0 ; i<n ; i++)
{
cout << a[i].num << endl;
}
a.erase(a.begin() , a.end());
b.erase(b.begin() , b.end());
tcase++;
|
So when i run my program with following input :
4
15
25
30
35
45
50
10
20
then my expected answer should be :
10
15
30
45
But my program is giving :
0
0
0
0
Where am i doing wrong ?
On line 7-8 you resize the vectors so that they contain n zero value. Then in the loop you add n additional values so vectors will have a size of 2*n.
After a has been sorted it will contain the values: 0 0 0 0 10 15 30 45
thanx @Peter87 . I am new to c++ STL container , thts y i took it differently.
Topic archived. No new replies allowed.