valarray
class look's same to array
class, can you please explain me where would I prefer valarray
over array
or vice versa?
-
1See http://stackoverflow.com/questions/1602451/c-valarray-vs-vector – johnsyweb Jan 22 '12 at 23:14
-
1It is `valarray`, not `vallaray`. They are not the same thing at all, you probably should not use `valarray` since it is so poorly thought as to render it useless. The difference between `array` and `vector` should suffice. – Alexandre C. Jan 22 '12 at 23:16
3 Answers
valarray
was already in C++03,array
is new in C++11valarray
is variable length,array
is not.valarray
is designed for numeric computations and provides plenty of operations including+
,-
,*
,cos
,sin
, etc...array
does not.valarray
has an interface to retrieve slices of the array (sub arrays),array
does not.

- 74,642
- 33
- 187
- 332

- 70,775
- 16
- 139
- 220
-
while all the answers are good and each has something more I wasn't know which to accept. so thanks to all of you!. – codekiddy Jan 22 '12 at 23:28
-
Permit me to add a couple of links about `array` and `array` versus `vector` http://en.cppreference.com/w/cpp/container/array and http://stackoverflow.com/questions/15079057/arrays-vs-vectors-introductory-similarities-and-differences – Reb.Cabin Aug 23 '15 at 14:57
valarray
is a dynamic data structure, whose size can change at runtime and which performs dynamic allocation. array
is a static data structure whose size is determined at compile time (and it is also an aggregate).
Don't use valarray
, though; just use a vector
instead.

- 464,522
- 92
- 875
- 1,084
-
1@zhermes: hm, maybe [check this question](http://stackoverflow.com/questions/1602451/c-valarray-vs-vector) for some background information. Essentially, standard algorithms and `vector` give you everything you need. – Kerrek SB Jan 23 '12 at 04:18
The class templates related to std::valarray<T>
are intended to support optimizations techniques known as expression templates. I haven't tried to do this but my understanding is that the specification doesn't quite require this and also doesn't really support this sufficiently. In general std::valarray<T>
is a fairly specialized class and it isn't really broadly used. Also, I think the template arguments support for std::valarray<T>
are a limited set (e.g. the numeric built-in types).
On the other std::array<T, n>
is a fixed size array supporting, as far as possible while being fixed size, the normal container interface. Essentially, std::array<T>
is a more convenient to use version of T[n]
.

- 150,225
- 13
- 225
- 380