C ++ replacement for std :: array

What is the best replacement for std::array<...> if I don't want to provide constexpr size? I thought it was best to use std::vector and make reserve(...) on it, but maybe I missed something?

+8
c ++ arrays vector
source share
3 answers

Yes, use std::vector .

So if your code

 std:array<int, 42> my_array; 

Replace it with

 std:vector<int> my_array(42); 

Note: you probably do not want to use reserve because it leaves vector empty. If you use std::array , your code does not have the concept of an empty array, so it is best represented by an instance of std::vector , which is populated during construction and never changes.

+7
source share

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

+17
source share

std::vector<> is probably your answer. I simply did not expect reserve() guarantee any speedup.

Bjarne Straustrup:

People sometimes worry about the cost of std :: vector growth gradually. I was worried about this and used reserve () to optimize growth. After measuring my code and repeatedly having trouble finding the benefits of the reserve () in real programs, I stopped using it, except when it was necessary to avoid the iterator being invalid (a rare case in my code). Again: measure through you optimize.

http://www.stroustrup.com/bs_faq2.html [See below "Why are standard containers so slow?" ]

+4
source share

All Articles