10

The question of vector vs valarray has already been asked here. My question refers specifically to the case of C++11. I have been reading a "A Tour of C++" and "The C++ Programming Language". Both books are written by Bjarne Stroustrup. In the first book the author explains that std::valarray should be preferred for numerical computing (Chapter 12). But then in the second book, in chapter 29, the author implements a Matrix class in terms of a std::vector.

Also by doing a bit of googling, it seems that performance-wise, a std::vector is just as fast as dynamically allocated "raw arrays".

So in the context of C++11, which container should be preferred for numerical computing?

My take on this would be that since std::vector provides fast access to its contents using the operator[] (which returns a reference to the data with no bounds checking) and that it is also safer to use a std::vector over a dynamically allocated array, std::vector should be preferred. Also, from C++11 onwards:

  • std::vector provides direct access to the underlying data using std::vector::data()
  • std::vector can be resized in order to use less memory using std::vector::shrink_to_fit()
manlio
  • 18,345
  • 14
  • 76
  • 126
BigONotation
  • 4,406
  • 5
  • 43
  • 72
  • 1
    Why don't you measure and verify which would be faster. In modern C++ world, std::vector should be used as default container unless we have reason not to do. – Mantosh Kumar Apr 24 '17 at 11:09

1 Answers1

3

valarray has the nice functionality, that you easily can apply mathematical functions element-wise and you have better slicing abilities. You can e.g. do v3 = sin(v2 + v1*3)

Nevertheless, if you really want to do scientific computing, consider using a library such as Eigen

yar
  • 1,855
  • 13
  • 26
  • 2
    I am aware of Eigen, Armadillo, MTL4 as well as the many other matrix libraries. One of the problem with these libraries is that their source code is completely opaque (in other words difficult as a learning tool, or if I wanted to change something myself). My question is also more on a conceptual basis. My understanding is that std::valarray is "unfinished business" – BigONotation Apr 24 '17 at 11:15