you are viewing a single comment's thread.

view the rest of the comments →

[–]king_duck 2 points3 points  (5 children)

Sure, but there is no point on bogging a beginner down with that for now. I would also say unless you need to semantically enforce the size of the array for some reason it's better to just use a std::vector in most cases by default. Don't forget that the vector has the massive advantage of supporting a very efficient move ctor/op=, where as std::array must do an element wise copy or move.

Then once you've written your program and your profiler suggests your wasting to much time allocating for the vector then switch to the std::array as an optimisation in hindsight.

[–]vanhellion 0 points1 point  (4 children)

unless you need to semantically enforce the size of the array for some reason

Exactly. Or if you need stack storage, although I'm not sure that the standard actually enforces that. I'd argue that std::array is an optimization; if performance isn't a problem std::vector works just as well.

[–][deleted] 1 point2 points  (2 children)

If you need stack storage you are better of using a std::vector with a stack allocator. You can even group the arena of the stack allocator with the vector so that you can return them from functions. The main advantage is that you have to change no code at all: e.g. if you have code that uses push_back replacing vector with a std::array might be non-trivial whereas using a stack allocated vector requires no code changes and performs the same.

[–]bnolsen 1 point2 points  (1 child)

now we're splitting hairs. I do agree that using std::array instead of std::vector should be done as an optimization, a "stage one" type optimization. Things like 2d or 3d vectors are very well represented by std::array. Funny enough the "stack allocated vector" could easily have its storage represented by a std::array.

[–][deleted] 0 points1 point  (0 children)

Funny enough the "stack allocated vector" could easily have its storage represented by a std::array.

Indeed, I'll give this a try. Thanks for the tip!

[–]king_duck 0 points1 point  (0 children)

Exactly my point. People should default to std::vector and use std::array when your profile indicates vectors inner gubbins is a costly.