Input and add elements to a list | C++ STL

C++ STL List - Adding elements to the list: Here, we are going to learn how to add elements to the list using C++ Standard Template Library?
Submitted by IncludeHelp, on October 30, 2018

To implement this example, we need to include "list" header that contains the functions for list operations.

To add the elements to the list, we use push_back() function, which is a library function of "list" header.

Example:

Here, we are declaring a list of string, reading string and adding them to the list.

#include <iostream>
#include <list>
#include <string>
using namespace std;

int main() 
{
	//declaring a list
	list<string> lstr;
	//declaring iterator to the list
	list<string>::iterator l_iter;
	
	//declaring string object
	string str;

	//input strings
	while(true)
	{
		cout<<"Enter string (\"EXIT\" to quit): ";
		getline(cin, str);
		if(str=="EXIT")
			break;

		//adding string to the list 
		lstr.push_back(str);
	}

	//printing list elements
	cout<<"List elements are"<<endl;
	for (l_iter = lstr.begin(); l_iter != lstr.end(); l_iter++)
		cout<< *l_iter<<endl;

	return 0;
}

Output

Enter string ("EXIT" to quit): New Delhi
Enter string ("EXIT" to quit): Mumbai
Enter string ("EXIT" to quit): Chennai
Enter string ("EXIT" to quit): EXIT
List elements are
New Delhi
Mumbai
Chennai

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT


Top MCQs

Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.