views:

105

answers:

1

In C++0x, what I want would be:

std::list<std::string> colours = {"red", "blue", "green", "grey", "pink", "violet"};

What's the easiest way in standard, non-0x C++?

+8  A: 
char const *x[] = {"red", "blue", "green", "grey", "pink", "violet"};
std::list<std::string> colours(x, x + sizeof(x) / sizeof(*x));

Or you can use the boost libraries and functions like list_of("a")("b")...

Johannes Schaub - litb
Incidentally, isn't that what C++0x's `std::initializer_list` facility does under the hood, more or less?
FredOverflow
@FredOverflow indeed :)
Johannes Schaub - litb
And if you're going to do it a lot: `template<int N, typename T> T *endof(T ( }`, which is part of what the C++0x `end` function template does.
Steve Jessop
See also [this answer](http://stackoverflow.com/questions/2552839/which-c-standard-library-wrapper-functions-do-you-use/2553081#2553081)...
sbi
@Steve: Shouldn't that be `size_t N` instead of `int N`?
FredOverflow
Sometimes I use `ptrdiff_t`. That's what `ptr1 - ptr2` yields (the int operand of `ptr + int` is signed and can be negative). Mostly I see `size_t` being used though which is reasonable too, I think :)
Johannes Schaub - litb
@FredOverflow: yes, in this case I think `size_t` is best. N is equal to the size of the object (in bytes) divided by something, so `size_t` certainly works. `int` might not be big enough for really big objects, and `ptrdiff_t` might not be able to express the difference between pointers at opposite ends of a really big object as a positive value, so I think probably should not be used as the size in the type of an array.
Steve Jessop