TITLE: array initialization with and without STL (Newsgroups: comp.lang.c++, 5 Jun 98) SOMEONE: c9707010@alinga.newcastle.edu.au > I just read a post where someone asked how to create an array in C++, > and how to initialize it using a for-loop, and then how to output it. > Fair enough request... KUEHL: dietmar.kuehl@claas-solutions.de The answer to the question is non-trivial at all! If you really want to *initialize* a built-in array with value opposed to assigning values after initialization, things are quite messy and even beyond most experts. Here is how this roughly looks like for an array of ints initialized with increasing values: #include int *array = static_cast(operator new[] (sizeof(int) * size)); for (int i = 0; i < size; ++i) new(array + i) int(i); // ...and, explicit construction requires explicit destruction: for (int i = size; --i > 0; ) array[i].~int(); operator delete[] (array); I hope I haven't messed up this example... I'm more used to do this with STL: std::vector array((count_iterator(0)), (count_iterator(10)); where 'count_iterator' is a simple input iterator like this one (drawn from the library I have written for me to aid in using STL): class count_iterator { public: count_iterator(int v): val(v) {} count_iterator &operator++ () { ++val; return *this; } count_iterator operator++ (int) { ++val; return count_iterator(val-1); } int operator* () const { return val; } bool operator== (count_iterator const &it) const { return val == it.val; } bool operator!= (count_iterator const &it) const { return val != it.val; } private: int val; }; (I typed this just in because I don't have the code with me). Anyway: Once you know how to write an iterator, it is much easier to use the STL than to initialize an array manually. ... and it is occasionally necessary to initialize an array, eg. because the type stored in the array does not have a default constructor. [SNIP]