How to define, initialize and print a list in C++

5 Answers

0 votes
#include <iostream>
#include <list>

using std::cout;
using std::endl;
using std::list;

int main()
{
	list<int> lst = { 1, 2, 3, 4, 5 };

	for (auto e : lst)
		cout << e << ' ';

	cout << endl;

	return 0;
}


/*
run:

1 2 3 4 5

*/

 



answered Apr 20, 2018 by avibootz
edited Apr 21, 2018 by avibootz
0 votes
#include <iostream>
#include <list>

using std::cout;
using std::endl;
using std::list;

int main()
{
	list<char> lst = { 'a', 'b', 'c', 'd' };

	for (auto e : lst)
		cout << e << ' ';

	cout << endl;

	return 0;
}


/*
run:

a b c d

*/

 



answered Apr 20, 2018 by avibootz
edited Apr 21, 2018 by avibootz
0 votes
#include <iostream>
#include <iterator>
#include <list>

using std::cout;
using std::endl;
using std::list;

int main()
{
	list<char> lst = { 'a', 'b', 'c', 'd', 'e' };

	copy(begin(lst), end(lst), std::ostream_iterator<char>(std::cout, " "));

	cout << endl;

	return 0;
}


/*
run:

a b c d e

*/

 



answered Apr 20, 2018 by avibootz
0 votes
#include <iostream>
#include <iterator>
#include <list>

using std::cout;
using std::endl;
using std::list;

int main()
{
	list<char> lst = { 'a', 'b', 'c', 'd', 'e', 'f' };

	list<char>::iterator p;

	while (!lst.empty()) {
		p = lst.begin();
		cout << *p << ' ';
		lst.pop_front();
	}

	cout << endl;

	return 0;
}


/*
run:

a b c d e f

*/

 



answered Apr 20, 2018 by avibootz
0 votes
#include <iostream>
#include <list>

using std::cout;
using std::endl;
using std::list;

int main()
{
	list<int> lst = { 1, 2, 3, 4, 5 };

	for (list<int>::iterator p = lst.begin(); p != lst.end(); p++)
		cout << *p << " ";

	cout << endl;

	return 0;
}


/*
run:

1 2 3 4 5

*/

 



answered Apr 21, 2018 by avibootz

Related questions

2 answers 184 views
2 answers 167 views
3 answers 209 views
2 answers 197 views
1 answer 160 views
1 answer 220 views
...