Vector Subscript Out of Range

Hi everyone, I have been stuck with this problem for the past two hours. The program asks the user for the names and values of their cars, stores them in tokens, and then puts the tokens into a vector. Then it prints out what the user entered. This program compiles and works up until the last part, at line 36. I don't know if anything is wrong with the for loop. Everything prints out fine, but I get a "Debug Assertation Failed!" error at line 1234. Expression: vector subscript out of range. Is there something I'm missing here? I don't know what's wrong. Thanks for your help and time.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
// ConsoleApplication2.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <string>
#include <vector>
using namespace std;

class Token 
{
public:
	string kind;
	double value;
};



int main()
{
	Token get_token();
	vector<Token> cars;
	while (true) 
	{
		string choice;
		cout << "Would you like to add a vehicle?\n";
		cin >> choice;
		if (choice == "yes" || choice == "Yes" || choice == "YES")
		{
			Token car = get_token();
			cars.push_back(car);
		}
		else if (choice == "no" || choice == "No" || choice == "NO")
			break;
	}
	for (int i = 0; i <= cars.size(); ++i)
	{
		cout << "Car " << i + 1 << " is a " << cars[i].kind << " and is worth $" << cars[i].value << ".\n";
	}
	system("pause");
    return 0;
}

Token get_token()
{
	Token tok;
	string kind;
	double value;
	cout << "Enter what type of vehicle you have.\n";
	cin >> kind;
	cout << "Enter what it's worth.\n";
	cin >> value;
	tok.kind = kind;
	tok.value = value;
	return tok;
}
Last edited on
Figured it out literally 10 minutes later. The for loop should be

for (size_t i = 0; i < things.size(); ++i)

instead of what it is now. This is because cars.size() is not an int, instead it is size_t, which equals some usual "unsigned" type.
Last edited on
The problem had nothing to do with the type. The problem was that valid indices in a vector fall into the range 0 to vectorSize - 1. By changing i <= cars.size() to i < cars.size() you stop yourself from trying to use cars.size() as an index (which is beyond the valid range of indices).
@booradley60

Wow, I tried that earlier, and it didn't work, but now it suddenly does. Thanks, I was going crazy
Topic archived. No new replies allowed.