markzzz
markzzz

Reputation: 47947

How to reserve memory for std::vectors within an std::array?

I have a std::array with a fixed number (numLines = 4) of std::vector; each std::vector will contains dynamic numbers of elements, which I know the max size of each std::vector (numMaxSteps = 32).

Thus:

std::array<std::vector<int>, numLines> mSequences;

Since I'm processing audio at higher rate, its mandatory for me to NEVER allocate memory during the process (hence, it introduces clicks and glitches).

But I'm not sure how to reserve memory of each std::vector on init.

Is there a way? Or I need to iterate each item of std::array and do.reserve(numMaxSteps)?

Note that I need to keep .size() at 0: only .capacity() need to grow up.

Upvotes: 0

Views: 222

Answers (4)

Extrapolating from your comment on Marshall's answer:

I only need a "fancy" way to reserve memory on init

It doesn't get any fancier than an IILE:

auto mSequences = []{
  std::array<std::vector<int>, nunLines> ret;
  for (auto& v : ret)
    v.reserve(maxCapacity);
  return ret;
}();

The lambda will be called automatically when it's time to initialize mSequences, and thanks to the wonders of NRVO will initialize it directly.

It can even be used to initialize complex objects declared const.

And if the idea of an IILE violates your coding standards, you can always make a named free function out of it.

Upvotes: 1

Jiri Volejnik
Jiri Volejnik

Reputation: 1089

You can also create a thin wrapper, if you don't mind writing a few more letters when accesing the vector:

struct vect32 {
    vect32() : vect(32) {}
    vector<int> vect;
};

array<vect32, 10> sequences;

sequences[0].vect.push_back(1);

Upvotes: 1

SergeyA
SergeyA

Reputation: 62553

What you describe here seems a perfect case for boost.static_vector.

This container allows you to pre-allocate compile-time size, but after that it supports push()/pop()/insert()/remove() etc and it's size function and iterators respect real run-time defined size.

Upvotes: 0

Marshall Clow
Marshall Clow

Reputation: 16670

Is there a way? Or I need to iterate each item of std::array and do .reserve(numMaxSteps)?

That's the way ;-)

But I agree with @bartop; with your needs, you should consider array<array<int, 32>> instead.

Upvotes: 0

Related Questions