Reputation: 15
I get crash when I try to run this program and error is Expression: vector subscriptout of range. What's the problem?
std::vector<DepositCustomers> Deposits; //depositcustomers is a class
std::ifstream fin("in.txt");
int contor = 1;
while (!fin.eof())
{
Deposits.resize(contor);
fin >> Deposits[contor];
contor++;
}
I've tried without resize and is the same thing.
Upvotes: 0
Views: 54
Reputation: 66441
The problem is that vectors, like arrays, are zero-indexed - if you have k
elements, they are indexed from 0
to k - 1
.
Thus, Deposits[contor]
is out of range for the vector, since it has contor
elements.
(You're lucky that you built a debug version that checks the indexing and found out quickly.)
You could fix this by writing Deposits[contor-1]
, but you have another issue.
That issue is that you're using .eof()
as a loop condition.
eof()
does not mean what you think it means, and you will store one element too many.
(See this Q&A for details.)
The "default" C++ input loop looks like
std::vector<DepositCustomers> Deposits;
std::ifstream fin("in.txt");
DepositCustomers customer;
while (fin >> customer)
{
Deposits.push_back(customer);
}
And a loop-free version is
std::vector<DepositCustomers> Deposits;
std::ifstream fin("in.txt");
using iterator = std::istream_iterator<DepositCustomers>;
std::copy(iterator(fin), iterator(), std::back_inserter(Deposits));
Upvotes: 1
Reputation: 16243
If you resize the vector to size 1
, then there is only room for 1 item in the vector. Since vectors use 0-based indexes, this item is at index 0
. So, when you try to place something at index 1
, it fails with the observed error.
To make the code work, you can make the following change :
fin >> Deposits[contor - 1];
Or probably better yet, use push_back
to save yourself the hassle of having to resize.
Upvotes: 4