user3857017
user3857017

Reputation: 275

Vector subscript out of range on iterator

#include <iostream>
#include <random>
#include <fstream>
#include <time.h>

using namespace std;

bool generateRandomValue()
{
    static std::default_random_engine e{};
    static std::uniform_int_distribution<int> d{ 0, 100 };

    bool headsTails = (d(e) > 50) ? true : false;

    return headsTails;
}

int main()
{
    clock_t tStart = clock();
    ofstream outputFile("output.txt");

    int totalHeads = 0;
    int totalTails = 0;

    vector<int> headList(100,0);
    vector<int> tailList(100,0);

    for (int out = 0; out <= 100; out++)
    {
        char result = '\0';
        int heads = 0, tails = 0;

        for (int i = 0; i < 100000; i++)
        {
            result = (generateRandomValue()) ? 'H' : 'T';

            if (result == 'H')
            {
                heads++;
            }

            else
            {
                tails++;
            }
        }

        outputFile << "Trial " << out << ": Heads: " << heads << " Tails: " << tails << endl << endl;
        headList.push_back(heads);
        tailList.push_back(tails);

    }

    for (vector<int>::iterator i = headList.begin(); i < headList.end(); i++)
    {
        totalHeads += headList[*i];
        totalTails += tailList[*i];
    }
    cout << "It took: " << (double)(clock() - tStart) / CLOCKS_PER_SEC << " seconds to calculate and execute this program.\n";
    outputFile << "Total number of heads: " << totalHeads << " Total number of tails: " << totalTails << endl;

    return 0;
}

Above is some code I've been messing with just to try out vectors (never used them in class). The code compiles in VS2015, but the program crashes with the following error: "Vector subscript out of range".

I assume this is telling me that at some point in my program a vector is attempting to be addressed at a location outside of its bounds. I haven't been able to tell whether the error is being thrown on my storage vectors or the iterator vector in the last for loop, and debugging doesn't work because the program crashes before it can begin to debug (weird that it isn't a compile time error then).

Upvotes: 1

Views: 1162

Answers (1)

Slava
Slava

Reputation: 44258

In this code:

for (vector<int>::iterator i = headList.begin(); i < headList.end(); i++)
{
    totalHeads += headList[*i];
    totalTails += tailList[*i];
}

iterator i iterates over all elements of headList vector. *i gives you that value (which is amount of heads in that iteration). You use that as an index for vectors totalHeads and totalHeads which seams to be wrong. Your loop should be:

for (size_t i = 0; i < headList.size(); i++)
{
    totalHeads += headList[i];
    totalTails += tailList[i];
}

Note: though this loop:

for (vector<int>::iterator i = headList.begin(); i < headList.end(); i++)

works for random access iterator, it is more common to write it in form:

for (vector<int>::iterator i = headList.begin(); i != headList.end(); ++i)

this way it will also work for forward iterator and you may change container type without modifying much code. ++i can be more efficient especially for iterator, not integral type.

Upvotes: 3

Related Questions