c++ - 迭代器上的 vector 下标超出范围

标签 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;
}

上面是一些我一直在搞乱的代码,只是为了尝试 vector (从未在类里面使用过)。代码在 VS2015 中编译,但程序崩溃并出现以下错误:“Vector subscript out of range”。

我假设这告诉我,在我的程序中的某个时刻,一个 vector 正试图在其范围之外的位置寻址。我无法判断错误是在我的存储 vector 上抛出还是在最后一个 for 循环中的迭代器 vector 上抛出,并且调试不起作用,因为程序在开始调试之前就崩溃了(奇怪的是它不是'然后是编译时错误)。

最佳答案

在这段代码中:

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

迭代器 i 迭代 headList vector 的所有元素。 *i 为您提供该值(即该迭代中的正面数量)。您将其用作 vector 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 可以更有效,尤其是对于迭代器,而不是整数类型。

关于c++ - 迭代器上的 vector 下标超出范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36091588/

相关文章:

c++ - vector push_back零成空 vector

c++11 - 在cuda中使用推力实验::pinned_allocator的奇怪行为

python - 了解 Python3.x 中的 izip

c++ - 为什么/何时不需要 __declspec( dllimport )?

c++ - 调用 c 函数时出现段错误

c++ - 为什么在 Windows 7 中调用 Beep 功能后听不到任何声音?

python - 迭代生成器时调用 iter 和 next

python - Qt中两个MainWindow()之间的通信

c++ - 无法在 STL 中打印一组 vector 的元素

c++ - std::vector operator[] 的不正确行为