Initializing list<string> in a constructor

M

mthread

Hi,
I would like initialize std::list<string> in the constructor
rather than using push_back function. I tried the following code, but
did not work,
list<string> fieldList = {"field", "field2"};

Kindly let me know how I can acheive this.
 
A

Alf P. Steinbach

* mthread:
Hi,
I would like initialize std::list<string> in the constructor
rather than using push_back function. I tried the following code, but
did not work,
list<string> fieldList = {"field", "field2"};

Kindly let me know how I can acheive this.

<code>
#include <iostream>
#include <list>
#include <string>

#define N_ELEMS( a ) (sizeof(a)/sizeof(*a))

int main()
{
using namespace std;
static char const* const names[] = { "field", "field2" };

list<string> fieldList( names, names + N_ELEMS( names ) );

typedef list<string>::const_iterator Iter;
for( Iter it = fieldList.begin(); it != fieldList.end(); ++it )
{
cout << *it << endl;
}
}
</code>

MinGW g++ 3.4.5 spews out a warning that some variable in its standard library
implementation might be used uninitialized. It seems to be compiler bug, not a
library code problem. Hm.


Cheers & hth.,

- Alf
 
J

Jorgen Grahn

Hi,
I would like initialize std::list<string> in the constructor
rather than using push_back function. I tried the following code, but
did not work,
list<string> fieldList = {"field", "field2"};

Kindly let me know how I can acheive this.

What Alf said. Also note that push_back is just one of many ways to
add things to a std::list -- read the documentation. If you don't have
any, read http://www.sgi.com/tech/stl/List.html.

/Jorgen
 
J

Juha Nieminen

mthread said:
list<string> fieldList = {"field", "field2"};

Btw, that *will* be possible exactly like that when the new C++
standard gets finished and compilers implement it.

Until then you'll have to do it like suggested in the other replies.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,479
Members
44,899
Latest member
RodneyMcAu

Latest Threads

Top