14

How do boost::numeric::ublas::vector and std::vector compare in runtime efficiency?

Is it safe to assume that I can convert an entire program from using std::vector to use boost::numeric::ublas::vector just by writing:

#include <boost/numeric/ublas/vector.hpp>
using namespace boost::numeric::ublas;

instead of #include<vector>? Can I just use boost vectors as if they were STL vectors in all aspects?

Do functions from <algorithm> work with boost vectors? Do they use the same iterators?

Do they work in C++0x? Do they work for range based loops?

Rafael S. Calsaverini
  • 13,582
  • 19
  • 75
  • 132

2 Answers2

24

These are completely orthogonal data types: the former represents the algebraic definition of 'vector' (a one-dimensional matrix), while the latter represents the computer science definition of 'vector' (a one-dimensional array).

They don't compare.

ildjarn
  • 62,044
  • 9
  • 127
  • 211
  • Gods! I searched the whole world thinking why isn't there a `push_back` in boost vector.. :) – Kashyap Aug 23 '12 at 18:15
  • note: stl algorithms still work. and you can use arithmetics by wrapping functions like `plus_assign` into a lambda http://www.boost.org/doc/libs/1_51_0/boost/numeric/ublas/functional.hpp – kirill_igum Mar 06 '13 at 10:29
10

You should only use ublas::vector if you want to do linear algebra operations, such as matrix vector multiplication etc. They do not provide the same functionality nor the same interface as std::vector. In terms of run-time efficiency, there is nothing, that I know of, that beats std::vector.

Johan Råde
  • 20,480
  • 21
  • 73
  • 110
  • Really? Cause I'm pretty sure linked lists like std::list beat vector for insertion and removal of elements. :p – wheaties Jun 09 '11 at 15:11
  • @wheaties I also thought so, but was shocked to see that vector is mostly good even for that. – Oleh Prypin Jun 09 '11 at 15:12
  • 1
    it really depends on the size. Insertion in the middle of a huge `std::vector` should be way slower than insertion in the middle of an equally huge `std::list`. – juanchopanza Jun 09 '11 at 15:20
  • see [here for evidence/benchmark](http://www.gotw.ca/gotw/054.htm) of what BlaXpirit is saying. Granted, size is the important element here. – rubenvb Jun 09 '11 at 15:31
  • 2
    @rubenvb : To be fair, that was benchmarked with MSVC 5, which was released in _Feb 1997_ -- not exactly current. ;-] – ildjarn Jun 09 '11 at 16:28
  • For inserting at the end of the container, one item at a time, on my Ubuntu laptop there is no size in which `list` outperforms `vector`. For inserting at the beginning of the container, `list` measurably outperforms `vector` for even modest (approximately 5000) size. – Robᵩ Jun 10 '11 at 17:30