Aayush Mahajan
Aayush Mahajan

Reputation: 4033

How are vectors(in C++) having elements of variable size allocated?

I wrote the following code to accept test-cases on a competetive programming website. It uses a vector input of the structure case to store the inputs for given test-cases all at once, and then process them one at a time( I have left out the loops that take the input and calculate the output because they are irrelevant to the question.)

#include<iostream>
#include<vector>
using namespace std;

struct case{
    int n, m;
    vector<int> jobsDone;
};

int main(){
    int testCase;
    cin>>testCase;
    vector<case> input;
    input.reserve(testCase); 

    //The rest of the code is supposed to be here
    return 0;
}

As I was writing this code, I realised that the working of input.reserve(t) in such a case where the element size is variable(since each instance of the structure case also has a vector of variable size) would be difficult. Infact, even if I had not explicitly written the reserve() statement, the vector still would have reserved a minumum number of elemtns.

For this particular situation, I have the following questions regarding the vector input:

Upvotes: 0

Views: 235

Answers (1)

David Schwartz
David Schwartz

Reputation: 182893

Every object type has a fixed size. This is what sizeof returns. A vector itself typically holds a pointer to the array of objects, the number of objects for which space has been allocated, and the number of objects actually contained. The size of these three things is independent of the number of elements in the vector.

For example, a vector<int> might contain:
1) An int * holding the address of the data.
2) A size_t holding the number of objects we've allocated space for
3) A size_t holding the number of objects contained in the vector.

This will probably be somewhere around 24 bytes, regardless of how many objects are in the vector. And this is what sizeof(vector<int>) will return.

Upvotes: 5

Related Questions