0
Why is this vector out of bounds?
Please explain https://code.sololearn.com/cbsOBpT5I4kv/?ref=app
3 Answers
+ 3
On line 13 - 14:
for (int i = 0; i <= SIZE; i++)
a.at(i) = 8;
You should use < not <=
If you try to access elements at index < 0 or index >= a.size() at method throws std::out_of_range exception
+ 2
Problem's here:
for (int i = 0; i <= SIZE; i++)
Because you use <=, you also ask for a[3] which doesn't exist.
0
First of all, if u just use push_back
The error would dissappear but a won't change and it always would be 5, 5, 5 because you declared it.
After that , in second for u said till i<=0 which need 4 element but a had 3 home for elements.
I used a temp as a container and push back to and that fixed.
Try this
include <iostream>
#include <vector>
using namespace std;
int main() {
const int SIZE = 3;
std::vector<int> a(3,5);
std::vector<int> temp;
std::cout << "a contains ";
for (int i = 0; i < SIZE; i++)
std::cout << a.at(i) << " ";
std::cout << '\n';
for (int i = 0; i <= SIZE; i++)
temp.push_back(8);
std::cout << "a contains ";
for (int i = 0; i < SIZE; i++)
std::cout << temp[i] << " ";
std::cout << '\n';
return 0;
}