c++ - "Iterator not dereferenceable"

标签 c++ iterator runtime runtime-error dereference

我喜欢代码让我头疼的时候。除了这个。我只是使用一种常用的算法用随机 double 填充一个 vector 。问题是,在编译之后,它给了我一个“Iterator not dereferenceable”运行时错误。这是我的代码路径:

-首先我创建了一个类的实例。

 Random rm;

-运行这个构造函数

    Random::Random() // Constructor
{
    this->cAR();
    this->min = 0; // Default: Sets minimum to zero
    this->max = RAND_MAX; // Default: Sets maximum to RAND_MAX

    fillVect(); // Fills vector
    this->numCount = num.begin();
}

-cAR 只是在下面的函数中设置一些值

void Random::cAR()
{
    this->num.clear();
    this->num.reserve(250);
    this->place = 0;
}

-现在是主要问题(我认为),我遍历 vector 并用生成的随机数填充它

void Random::fillVect()
{
    srand(time(NULL));
    vector<double>::iterator counter;
    for (counter = this->num.begin(); counter <= num.end(); counter++)
    {
        *counter = (((double) rand() / (double) RAND_MAX) * (this->max - this->min)) + this->min;
    }

    shuffle();
}

- 这应该用随机数填充 vector (顺便说一句,这是一个“ double ”类型的 vector )。然后,我用这个语句调用 vector 中的下一个数字(应该是开头的第 0 个索引)

double r = rm.nextDbl();

-在这个函数中定义

double Random::nextDbl()
{
    double temp = *numCount;
    return temp;
    numCount++;
    place++;
}

在我看来,这是一条正确的代码路径。现在,我只写了 2 年的代码,而且在一所真正的大学里只有 1 年的学生,所以我的问题是,为什么它会给我这个运行时错误?我事先感谢任何帮助。

最佳答案

您正在取消引用 end() 迭代器,这是无效的:

 for (counter = this->num.begin(); counter <= num.end(); counter++)

这应该是:

for (counter = this->num.begin(); counter != num.end(); ++counter)

关于c++ - "Iterator not dereferenceable",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26953497/

相关文章:

c++ - 如何部分禁用 C4244

list - 使用每组的一个数字查找多组中的数字总和

python - 读取csv数据时pythoncode中的StopIteration错误

android - 如何在没有 Eclipse 的情况下向 APK 添加 jar 并使 APK 引用它?

c# - .NET 运行时处理通用代码

java - 为什么 C++ 允许直接从子类中调用祖父类方法?

c++ - 为什么我可以通过指针访问私有(private)数据成员,我应该这样做吗?

c++ - 顺序容器 || C++ Primer 第五版习题 9.22

java - 算法运行时间

c++ - 将 std::shared_ptr 与 clang++ 和 libstdc++ 一起使用