Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11: should I use valarray or vector for numerical computing

Tags:

c++11

valarray

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()
like image 212
BigONotation Avatar asked Apr 24 '17 07:04

BigONotation


People also ask

Is valarray faster than vector?

valarray is faster and vector is more flexible.

What is Valarray?

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.


1 Answers

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

like image 166
yar Avatar answered Sep 21 '22 07:09

yar