I am trying to find a way to let the user define the length of an int vector, which is a private member of a class, and then insert all of the numbers through the console, however, I did not find any overload specifically made for vectors. Here is my code, which gets: "exception: std::out_of_range at memory location." when it reached the for loop.
#include <iostream>
#include<vector>
using namespace std;
class List
{
private:
vector<int> numbers;
public:
List(){vector<int> numbers = {};}
friend istream& operator>>(istream& i, const List& l);
};
istream& operator>>(istream& i, const List& l)
{
int help{ 0 };
i >> help; //I used help to define the amount of numbers to be added
for (int i{ 0 }; i < help; i++) //exception: std::out_of_range at memory location
i >> l.numbers.at(i);
return i;
}
int main()
{
List list;
cin >> list;
return 0;
}
I've removed operator<< to decrease the code, if you need it, I will send it. Any help, solution or link to the place, where I can learn how to solve this would be greatly appreciated.
int help{ 0 };
i >> help; //I used help to define the amount of numbers to be added
for (int i{ 0 }; i < help; i++) //exception: std::out_of_range at memory location
i >> l.numbers.at(i);
return i;
Will most definitely cause an out-of-range exception. The std::vector
is empty, so it will set the element at i
(which is out of range) to something. Also, the i
in the loop overshadows the std::istream
i
.
You can change that to this:
int help{ 0 };
i >> help; //I used help to define the amount of numbers to be added
l.numbers.resize(help);
for (int counter{ 0 }; counter < help; counter++) //exception: std::out_of_range at memory location
i >> l.numbers.at(counter);
return i;