Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ alternatives to std::array when the size is fixed, but not a constexpr?

Tags:

c++

arrays

vector

What is the best replacement for std::array<...> if I don't want to have to provide constexpr size? I figured it would be best to just use std::vector and do reserve(...) on it, but maybe I'm overlooking something?

like image 569
Enn Michael Avatar asked Jun 16 '16 19:06

Enn Michael


People also ask

What is an alternative to array in C++?

std::vector is the correct replacement for most cases, QVector is preferable for code that uses Qt, while std::array can be used in those cases where granular memory control is critical.

How do I get the size of an array in C++?

In C++, we use sizeof() operator to find the size of desired data type, variables, and constants. It is a compile-time execution operator. We can find the size of an array using the sizeof() operator as shown: // Finds size of arr[] and stores in 'size' int size = sizeof(arr)/sizeof(arr[0]);


2 Answers

std::vector should be the correct container of choice, if the size needs to be determined at runtime.

like image 106
2 revs, 2 users 67% Avatar answered Nov 15 '22 16:11

2 revs, 2 users 67%


Yes, use std::vector.

So if your code is

std:array<int, 42> my_array;

Replace it by

std:vector<int> my_array(42);

Note: you probably don't want to use reserve, because it leaves the vector empty. If you are using std::array, your code doesn't have the concept of empty array, so it's best represented by a std::vector instance that is filled at construction, and never resized.

like image 28
anatolyg Avatar answered Nov 15 '22 16:11

anatolyg