Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reseve memory for inner vector in a std::vector<std::vector<TYPE>>

I like to reserve memory for the inner vector in a std::vector<std::vector<TYPE>>, in order to avoid a lot of single memory allocations during a subsequent push_back. I don't know the innerSize of the vector exactly, but I can give a good estimate.

std::resize can be used as

vecs.resize(outerSize, std::vector<TYPE>(innerSize));

where outerSize and innerSize are given ints. This does not work for me, because the default constructor is not applicable. However std::reserve does not provide an interface like this.

Is this a good way to reserve memory for all inner vectors?

vecs.resize(outerSize);
for (auto &elem : vecs) {
    elem.reserve(innerSize);
}
like image 744
schorsch312 Avatar asked May 14 '18 07:05

schorsch312


1 Answers

The only alternative that I can think of is that you create a wrapper class around the inner std::vector; which reserves it on construction. Leading to something like

struct TableRow {
    std::vector<TYPE> data;
    TableRow() {
        data.reserve(SIZE);
    }
}

std::vector<TableRow> myVectorOfVectors;

The other gain from this is that your inner vector gets a name that you can understand (such as TableRow); but the downside is that unless you're willing to play the game of inheriting std::vector (if in doubt; don't do this); your usage of the wrapper class will have to be a little awkward since you'll need to add a .data or something of that ilk.

As others have said though; your way is perfectly fine.

like image 171
UKMonkey Avatar answered Oct 18 '22 08:10

UKMonkey