6

Yes, this has been asked before, and the answer has been:

valarrays (value arrays) are intended to bring some of the speed of Fortran to C++. You wouldn't make a valarray of pointers so the compiler can make assumptions about the code and optimise it better. (The main reason that Fortran is so fast is that there is no pointer type so there can be no pointer aliasing.)

or:

valarray is also supposed to eliminate any possibility of aliasing [...]

But these answers make no sense to me.

valarray and vector are class templates, and as such, they don't even exist until instantiated.
And of course, a vector<int> doesn't cause aliasing issues any more than valarray<int> does.

Given this, what was the purpose of valarray, and why did they not simply put the same functionality into vector instead?

Community
  • 1
  • 1
user541686
  • 205,094
  • 128
  • 528
  • 886
  • 2
    Valarray is a half-baked feature of the STL. The goal was to provide an array class where operations could be executed in batch, with possible loop fusion for machines where it makes sense. The closer useful thing which exists nowadays for C++ is [Intel ABB](http://software.intel.com/en-us/articles/intel-array-building-blocks). – Alexandre C. Sep 25 '12 at 10:07
  • According to H. Sutter, it's a leftover from the pre-STL days before the C++98 standard was finalized. See e.g. http://www.gotw.ca/publications/mill01.htm – Some programmer dude Sep 25 '12 at 10:08

2 Answers2

11

Separation of concern? A vector and a valarray solve different problems. Quoting from the standard, a vector is a (§23.3.6.1 [vector.overview] p1)

... sequence container that supports random access iterators. In addition, it supports (amortized) constant time insert and erase operations at the end; insert and erase in the middle take linear time. Storage management is handled automatically, though hints can be given to improve efficiency.

while a valarray is a (§26.6.2.1 [template.valarray.overview] p1)

... one-dimensional smart array, with elements numbered sequentially from zero. It is a representation of the mathematical concept of an ordered set of values. The illusion of higher dimensionality may be produced by the familiar idiom of computed indices, together with the powerful subsetting capabilities provided by the generalized subscript operators.

As you can see, they serve different purposes. A vector is a generalized dynamic array, while a valarray represents a set of values. It's also not resizeable and only assignable.

johnsyweb
  • 136,902
  • 23
  • 188
  • 247
Xeo
  • 129,499
  • 52
  • 291
  • 397
  • `valarray` can be resized (but its contents may be lost) http://en.cppreference.com/w/cpp/numeric/valarray/resize – sastanin May 10 '15 at 21:58
6
  • valarray has the slice mechanism

  • valarray is expected to be implemented using expression template for its numerical operators

AProgrammer
  • 51,233
  • 8
  • 91
  • 143