迭代器

时间:2016-03-18 18:17:07

标签: c++ vector iterator outofrangeexception

#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;
}

以上是一些代码我一直在试图尝试向量(从未在课堂上使用它们)。代码在VS2015中编译,但程序崩溃时出现以下错误:&#34;矢量下标超出范围&#34;。

我认为这告诉我,在我的程序中的某个时刻,向量试图在其边界之外的位置处寻址。我还没有能够判断错误是在我的存储向量或最后一个for循环中的迭代器向量上抛出,并且调试不起作用,因为程序在它开始调试之前崩溃(很奇怪)它不是编译时错误。)

1 个答案:

答案 0 :(得分:3)

在此代码中:

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

迭代器i遍历headList向量的所有元素。 *i为您提供该值(该迭代中的头数)。您将其用作向量totalHeadstotalHeads的索引,这些向量错误。你的循环应该是:

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

注意:虽然这个循环:

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

适用于随机访问迭代器,以表格形式编写它更为常见:

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

这样它也可以用于前向迭代器,你可以在不修改很多代码的情况下更改容器类型。 ++i可以更有效,特别是对于迭代器而不是整数类型。