Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace fixed size arrays with std::array?

Working with legacy code, I asked myself should I replace fixed sized C-style arrays with the new std::array? E. g.

static const int TABLE_SIZE = 64; double table[TABLE_SIZE]; 

replace with

std::array<double, TABLE_SIZE> table; 

While I see the benefits from using std::vector for variable size arrays, I don't see them with fixed size. table.size() is known anyways, std::begin(), std::end() as free functions can be used for STL-algorithms with C-style arrays too. So besides being more standard compliant, do I miss more benefits? Is it worth the work to replace all occurrences or is it considered to be best practice?

like image 248
DaBrain Avatar asked Mar 21 '14 23:03

DaBrain


People also ask

Is std :: array fixed size?

std::array is a container that encapsulates fixed size arrays. This container is an aggregate type with the same semantics as a struct holding a C-style array T[N] as its only non-static data member. Unlike a C-style array, it doesn't decay to T* automatically.

Can we use alternative of array in C++?

Yes, in Turing, and other languages, where arrays are either well-implemented, or there's simply no decent alternative. The vector class in the Standard Template Library provides a more flexible, powerful alternative to using arrays.

What are 2 typical problems with fixed array sizes?

Because fixed arrays have memory allocated at compile time, that introduces two limitations: Fixed arrays cannot have a length based on either user input or some other value calculated at runtime. Fixed arrays have a fixed length that can not be changed.

Is array always fixed size?

The main difference between Array and ArrayList in Java is that Array is a fixed length data structure while ArrayList is a variable length. You can not change length of Array once create, but ArrayList can re-size itself.


1 Answers

AFAIK std::array just provides a nicer STL-like interface to deal with rather than normal C-arrays. In terms of performances and capabilities the two choices boil down to be pretty much the same but std::array can be used as a standard container.

Another feature: they might be treated like tuples since they provide tuple-like access functions.

Last but not the least as user2079303 noticed: if your code is going to be used by novice programmers, it can prevent the array decaying process when passing it as an argument.

If you're wondering if you should just replace all your C-style arrays with std::arrays, the answer is yes if you're going to exploit some of the newly available features and/or rewrite some of your code to take advantage of those capabilities. If you're just plain substituting C-arrays with std::arrays (without touching anything else) it might not be worth it.

like image 153
Marco A. Avatar answered Oct 12 '22 12:10

Marco A.