That's because you're calling the parameterized constructor once to create a prototype object. After that the copy constructor is being called. As in the documentation:
If the current size is less than count, additional elements are appended and initialized with copies of value.
If you want to add N new items then AFAIK you need to use push_back
(or preferably, emplace_back
in C++11) in a loop:
#include <iostream>
#include <vector>
using namespace std;
struct Object {
int alpha;
int beta;
Object (int alpha, int beta) : alpha (alpha), beta (beta) {}
};
int main() {
vector<Object> objs;
int nObjects = 5;
for (int i = 0; i < nObjects; i++) {
objs.emplace_back(rand(), rand());
}
for (Object & o : objs) {
cout << o.alpha << "," << o.beta << "\n";
}
}
There are some routines in <algorithm>
like generate_n to overwrite a range of items using the result of a function that is called repeatedly. But I don't think that's what you want here; as it requires the collection to already have objects in it that you overwrite. That's my impression. So when adding new items to the end when each object needs to be generated uniquely, I think emplace_back
is the way to go.
As an additional note, always remember to reduce your example. If it's not about memory allocation, don't include a new. If two fields are enough, don't use four. And always if possible, submit your question in the form of a "Minimal, Complete, Verifiable Example" (like the code above).