How to display list items in vC ++?
2 answers
Are you following the following, or want to know how to read from console input and store in a string (which is then stored in a list I guess), this is the first time how to store strings in a list (and output the contents of the list):
#include <iostream>
#include <string>
#include <list>
using std::string;
using std::list;
using std::cout;
using std::endl;
list<string> strlist;
strlist.push_back(string("string one"));
strlist.push_back(string("string two"));
strlist.push_back(string("and so on"));
for (list<string>::iterator it = strlist.begin(); it != strlist.end(); ++it)
{
std::cout << (*it) << std::endl;
}
Note. The list contains a copy of the strings, which means that you copy the strings when you assign them to the list and when you return them from the list. To avoid this, you can allocate memory for the string and only keep the pointers in the list:
list<string*> ls;
ls.push_back(new string("string one"));
etc.
This works, and above is a more detailed description of how to access the elements of the list, in the copy algorithm it all happens behind the scenes:
copy( strlist.begin(), strlist.end(), ostream_iterator<string>( cout, ", " ) );
+3
a source to share
You can use std :: copy inand std :: ostream_iterator into copy the items to the output like so:
#include <iostream>
#include <string>
#include <list>
#include <algorithm>
int main( int, char*[] )
{
using namespace std;
list<string> mylist;
mylist.push_back( "String1" );
mylist.push_back( "String2" );
mylist.push_back( "String3" );
copy( mylist.begin(), mylist.end(), ostream_iterator<string>( cout, ", " ) );
}
0