5

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++?

Dataflashsabot
  • 1,369
  • 5
  • 19
  • 24

1 Answers1

11
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
  • 496,577
  • 130
  • 894
  • 1,212
  • 1
    Incidentally, isn't that what C++0x's `std::initializer_list` facility does under the hood, more or less? – fredoverflow Sep 16 '10 at 12:35
  • 1
    And if you're going to do it a lot: `template T *endof(T (&ra)[N]) { return ra + N; }`, which is part of what the C++0x `end` function template does. – Steve Jessop Sep 16 '10 at 12:46
  • See also [this answer](http://stackoverflow.com/questions/2552839/which-c-standard-library-wrapper-functions-do-you-use/2553081#2553081)... – sbi Sep 16 '10 at 12:48
  • @Steve: Shouldn't that be `size_t N` instead of `int N`? – fredoverflow Sep 16 '10 at 12:58
  • 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 Sep 16 '10 at 13:02
  • @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 Sep 16 '10 at 15:05