# Is using std::valarray considered good practice?

C++ has had the std::valarray class since the C++98 standard. It is meant to facilitate numerical computations, providing the sort of operations one would expect of a class implementing the mathematical concept of a vector space (with minor oddities like operator==, which returns a vector of booleans instead of a single bool).

Yet, I don't see that class widely used, either as a standalone or as the basis for more sophisticated implementations of vectors. What is the community's opinion on this class? What is the experience we as a community have with it, both positive and negative?

• I was under the impression that it was designed for vector architectures that never really took off. So rather than good or bad practice, the question to me is does your architecture + compiler give a more effective computation when (say) you want to compute the logarithm of every element of an array? Oct 7 '19 at 0:36
• never used it so far, but some compilers seem to be able to optimize them (stackoverflow.com/questions/6850807/why-is-valarray-so-slow), also see this answer: (stackoverflow.com/a/1602787) Oct 7 '19 at 8:32
• @MPIchael -- ah, thanks for the links, that's quite interesting! Oct 7 '19 at 14:43
• In the computer graphics community it is pretty common to use the Eigen C++ library, which offers a nice syntax for both vectors and matrices.
– user3883
Oct 11 '19 at 10:51

I can only give you my personal impressions and opinions. My impression is that many people find the class somewhat redundant, because functionally it doesn't really give you much that the vector class doesn't. The algorithms it implements will have the same asymptotic complexity, although optimizations can in principle be made, because it restricts the type of the template parameter to specific numerical types.
When you value a natural syntax, which I do, but many C++ developers seem to find of secondary importance, I think there are important advantages to the valarray class. When programming in Python, I make heavy use of NumPy, and syntactically the valarray class is much closer to a NumPy array than a vector is, which I like (built-in complete set of pointwise operations, slicing, etc).
• It's the syntax I'm interested in. std::valarray looks a lot like an element of a vector space, allowing addition, subtraction, etc. That's in contrast to std::vector which, well, is not a vector. Oct 7 '19 at 14:26