range error

Hi eveyone, as a beginner in both this forum and c++ please bear with me. I have two vectors of the same type which is a class, one copies part of the other vector. the problem is whenever i try to copy and update the second record and subsequent records of the second vector copied from the first vector an out of range error is thrown.

NB the program only works with the first record only
//this my code
void purchase(vector<Item> &v, vector<Item> &p){

int index;
int buy_units = 0;
int new_units = 0;
int units = 0;

cout << "Please enter the index of the item\n";
cin >> index;
units = v[index-1].get_units();

cout << "Please enter the number of units you want to purchase\n";
cin >> buy_units;

if (buy_units <= units){
record = v[index-1];
new_units = units - buy_units;
p[index-1].set_units(buy_units);//the error happens when i try to update here
else if (units == 0) {
cout << "The item is currently out of stock\n";
else if (buy_units > units) {
cout << "The units in stock is not enough\n";
Last edited on
The problem is that p.push_back(record); does not add the record at the specified index. If you want this use resize(). Otherwise use back():


p[index-1].set_units(buy_units);//the error happens when i try to update here


p.back().set_units(buy_units);//This will modify the last added record

I'd recommend to try and avoid those kind of errors, as for their high complexity which makes them are to be detected. It can be a real pain sometimes, and although there programs, as checkmarx, that kind of helps with it, I'd recommend avoiding them. It's achievable by some good practicing. Good luck!
Topic archived. No new replies allowed.