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©;
// l.push_back(d);
// l.push_back(e);
// l.sort();

return 0;

}

Please either format your code or (better!) link to your submission - the forum software has mangled it and it won’t compile! :slight_smile:

Also: Please find the problem in my program - #2 by dontcheckme

(Expected output)
5
1
3
5
6
7

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

https://www.codechef.com/problems/TSORT

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. :sweat_smile:

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 :slight_smile:

Sir, can you please elaborate :sweat_smile:

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

Your Output

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

Your Code, ACfied

#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©;
// l.push_back(d);
// l.push_back(e);
// l.sort();

return 0;
}

Thank you very much ,It worked :grinning:

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