I'm trying to create a vector where each element is a multiple of 3 below 1000. I tried two ways, only one of which worked. The non-functioning way was:
int main() {
vector<int> multiples_of_three;
for (int i = 0; i <= 1000/3; ++i)
multiples_of_three[i] = 3*i;
cout << multiples_of_three[i] << "\n";
}
That gave an out of range error specifically on multiples_of_three[i]
. This next bit of code worked:
int main() {
vector<int> multiples_of_three(334);
for (int i = 0; i < multiples_of_three.size(); ++i) {
multiples_of_three[i] = 3*i;
cout << multiples_of_three[i];
}
So if I defined the size of the vector I could keep it within it's constraints. Why is it that if I try and let the for loop dictate the number of elements I get an out of range error?
Thanks!