stl::list static member initialization
Hi all,
I want to initialize a static stl list of strings with some predifined string values(hardcoded).
I declared the list in my class like this:
static const list<string> my_list;
(I want to do something like static const list<string> my_list("VAL1","VAL2","VAL3","VAL4") but this is not working.)
Does someone know how to solve this problem?
Thank you very much!
Cristina
[445 byte] By [
mariacri] at [2007-11-19 18:30:08]

# 1 Re: stl::list static member initialization
write a function that returns a list.
this is all in the .cpp file for your class
//ANONYMOUS NAMESPACE
namespace
{
std::list<std::string> InitializeList()
{
std::list<std::string> temp;
temp.push_back("VAL1");
...
...
temp.push_back("VAL4");
return temp;
}
}
const list<string> YOUR_CLASS::my_list = InitializeList();
# 2 Re: stl::list static member initialization
Use a vector instead of a list.. you can use the reserve member function to keep the size to what you want .. also accessing members would be faster.. Regards.
# 3 Re: stl::list static member initialization
write a function that returns a list.
this is all in the .cpp file for your class
//ANONYMOUS NAMESPACE
namespace
{
std::list<std::string> InitializeList()
{
std::list<std::string> temp;
temp.push_back("VAL1");
...
...
temp.push_back("VAL4");
return temp;
}
}
const list<string> YOUR_CLASS::my_list = InitializeList();
Thank you, but I acctually I was trying to avoid the push_method :).
I was hoping there is a simpler way of doing it (without push).
Cristina
# 4 Re: stl::list static member initialization
1. What difference does it make if you use push_back. Never understand stuff like this.
2. Why not just use a c-style array? It is constant and so will not change size. You will
be able to initialize that in the way you want
# 5 Re: stl::list static member initialization
Thank you, but I acctually I was trying to avoid the push_method .
I was hoping there is a simpler way of doing it (without push).
For each element inserted, push_back() should operate in constant time. If you want the code to be 'simpler', you could do something like:
//ANONYMOUS NAMESPACE
namespace
{
std::list<std::string> InitializeList()
{
const char* strs[] = {"VAL1", "VAL2", "VAL3", "VAL4"};
return std::list<std::string>(strs, strs + 4);
}
}
const list<string> YOUR_CLASS::my_list = InitializeList();