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::shrink_to_fit()
valarray is faster and vector is more flexible.
class valarray; std::valarray is the class for representing and manipulating arrays of values. It supports element-wise mathematical operations and various forms of generalized subscript operators, slicing and indirect access.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With