codekiddy
codekiddy

Reputation: 6137

What is the difference between std::valarray and std::array

valarray class look's same to array class, can you please explain me where would I prefer valarray over array or vice versa?

Upvotes: 20

Views: 9121

Answers (3)

Yakov Galka
Yakov Galka

Reputation: 72479

  • valarray was already in C++03, array is new in C++11
  • valarray 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.

Upvotes: 24

Dietmar Kühl
Dietmar Kühl

Reputation: 153840

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].

Upvotes: 6

Kerrek SB
Kerrek SB

Reputation: 477070

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.

Upvotes: 6

Related Questions