# Confusing output(partial correct)

#include
#include
using namespace std;
void display(list &lst)
{
list :: iterator iter;

``````for(iter=lst.begin();iter!=lst.end();iter++)
{
cout<<*iter<<endl;
}
``````

}

int main() {
int number;
cin>>number;
list l(number);
for(int i=1;i<=number;i++)
{
int a;
cin>>a;
l.push_back(a);
}
l.sort();
display(l);

// cin>>a>>b>>c>>d>>e;
// l.push_back(a);
// l.push_back(b);
// l.push_back(d);
// l.push_back(e);
// l.sort();

``````return 0;
``````

}

(Expected output)
5
1
3
5
6
7

(My output)
0
0
0
0
0
5
1
3
5
6
7

Unscrambling this - you’ve created a `std::list` consisting of `number` 0's, then you’re reading in and appending to it another `number` values.

I have edited my output.Please take a look.

I don’t get the same output with your solution (assuming I’ve demangled it correctly, and assuming you are using the sample input,

``````5
5
3
6
7
1
``````

as input) - I have one less 5. Your expected output also has an extra 5 in it compared to the sample output according to the Problem.

I already told you what’s wrong in the comment above

``````int number;
cin>>number;
list l(number); // l is a list of 0's, length of list is 'number'
for(int i=1;i<=number;i++)
{
int a;
cin>>a;
l.push_back(a); // The input is appended here
}
``````

Input

``````5
1
2
3
4
5
``````

Expected Output

``````1
2
3
4
5
``````

``````0
0
0
0
0
1
2
3
4
5
``````

Now, to correct your solution, try making the following changes.

``````list l(number);
// Shall be replaced with
list l;
// I am not sure
``````
1 Like

``````#include <bits/stdc++.h>
using namespace std;
void display(list<int> &lst)
{
list<int> :: iterator iter;

for(iter=lst.begin();iter!=lst.end();iter++)
{
cout<<*iter<<endl;
}
}

int main() {
int number;
cin>>number;
list<int> l;
for(int i=1;i<=number;i++)
{
int a;
cin>>a;
l.push_back(a);
}
l.sort();
display(l);

// cin>>a>>b>>c>>d>>e;
// l.push_back(a);
// l.push_back(b);
// l.push_back(d);
// l.push_back(e);
// l.sort();

return 0;
}
``````

Thank you very much ,It worked

But can you please tell me why list l(number) didn’t work but list l worked?

``````list<int> mylist(n);
// It will initialise a list of 'n' integers, all of them being 0
// I am not sure
``````
``````list<int> mylist;
// Empty List of Integers
// I am not sure
``````
1 Like

ok,
thank you very much