Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11 std::array

I'd like to use std::array from C++11 as a field of my own class. It takes two template parameters (first defines type of data, second defines size of an array).

But I know the second parameter only in constructor. I'm not familiar with C++11 standard, but I suppose that it's impossible to set a template parameter during execution.

Are there any alternatives for std::array? std::vector is probably a little too much, cause I will never change the size of it.

like image 555
Dejwi Avatar asked Jan 31 '12 14:01

Dejwi


People also ask

What is std :: array C++?

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.

What is the point of std :: array?

std::array provides many benefits over built-in arrays, such as preventing automatic decay into a pointer, maintaining the array size, providing bounds checking, and allowing the use of C++ container operations.

How do you declare an array in C++ STL?

The general syntax of declaring an array container is: array<object_type, size> array_name; The above declaration creates an array container 'array_name' with size 'size' and with objects of type 'object_type'.

Is std :: array initialize?

std::array contains a built-in array, which can be initialized via an initializer list, which is what the inner set is. The outer set is for aggregate initialization.


1 Answers

std::vector is the simplest thing to use; although as you say, it does waste a few bytes if you'll never need to resize it.

std::unique_ptr<T[]>, initialised using the result of new T[size], would be the most efficient thing; it should be the same size as a pointer, and will delete the allocated memory for you when it's destroyed. It's not copyable, though; you'll need to provide a copy constructor for your class if you want it to be copyable. It's also less convenient than std::array and std::vector, since it doesn't have the interface of a standard container. You could perhaps write a STL-style wrapper for it if you need that; but I'd just use std::vector in that case.

like image 118
Mike Seymour Avatar answered Sep 27 '22 20:09

Mike Seymour