I need to fill a vector in with particular values. I find that the below code works, except in that a.size()
fails to change from 0. Adding a resize call after I put in the elements takes almost twice as long. It seems there should be an O(1) way to update the size, since I don't need to change any elements. Is there? Should I just not bother?
#include <iostream>
#include <vector>
#include <math.h>
using namespace std;
int main()
{
int n = 1e9;
vector<float> a;
a.reserve(n);
for (int i=0; i<n; i++)
a[i] = i;
cout << a[2]; //successfully prints as 1
cout << a.size(); //confusingly prints as 0
}
Edit: this is not a duplicate, as the linked question does not address benchmarking. It simply asks the difference in reserve and resize, which I am not asking about. This code works, and fast, but has the ugly side effect of leaving size() "incorrect."