c++11 std::array vs static array vs std::vector

PinkFloyd picture PinkFloyd · Sep 18, 2013 · Viewed 20.6k times · Source

First question, is it a good thing to start using c++11 if I will develop a code for the 3 following years?

Then if it is, what is the "best" way to implement a matrix if I want to use it with Lapack? I mean, doing std::vector<std::vector< Type > > Matrix is not easily compatible with Lapack.

Up to now, I stored my matrix with Type* Matrix(new Type[N]) (the pointer form with new and delete were important because the size of the array is not given as a number like 5, but as a variable).

But with C++11 it is possible to use std::array. According to this site, this container seems to be the best solution... What do you think?

Answer

Bartek Banachewicz picture Bartek Banachewicz · Sep 18, 2013

First things first, if you are going to learn C++, learn C++11. The previous C++ standard was released in 2003, meaning it's already ten years old. That's a lot in IT world. C++11 skills will also smoothly translate to upcoming C++1y (most probably C++14) standard.

The main difference between std::vector and std::array is the dynamic (in size and allocation) and static storage. So if you want to have a matrix class that's always, say, 4x4, std::array<float, 4*4> will do just fine.

Both of these classes provide .data() member, which should produce a compatible pointer. Note however, that std::vector<std::vector<float>> will NOT occuppy contiguous 16*sizeof(float) memory (so v[0].data() won't work). If you need a dynamically sized matrix, use single vector and resize it to the width*height size.

Since the access to the elements will be a bit harder (v[width * y +x] or v[height * x + y]), you might want to provide a wrapper class that will allow you to access arbitrary field by row/column pair.

Since you've also mentioned C-style arrays; std::array provides nicer interface to deal with the same type of storage, and thus should be preferred; there's nothing to gain with static arrays over std::array.