0

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.

c-a
  • 82
  • 1
  • 11
Bogdy
  • 15
  • 3

2 Answers2

4

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.

Sander De Dycker
  • 15,403
  • 1
  • 31
  • 37
1

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));
molbdnilo
  • 55,783
  • 3
  • 31
  • 71