简体   繁体   English

Eratosthenes C ++筛-内存范围错误

[英]Sieve of Eratosthenes C++ - Range Error at memory

I'm working on this simple code to use the Sieve, but there is an error that stops the program from compiling. 我正在研究使用Sieve的简单代码,但是有一个错误使程序无法编译。 Below you find the code: 在下面找到代码:

// sieve_of_erathosthenes.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "../../Library/std_lib_facilities.h"

int main()
{
    // Create a boolean array "prime[0..n]" and initialize
    // all entries it as true. A value in prime[i] will
    // finally be false if i is Not a prime, else true.
    int n = 30;
    vector<int>prime;

    for (size_t i = 0; i < n; i++) {
        prime.push_back(true);
    }

    for (int p = 2; p*p <= n; p++)
    {
        // If prime[p] is not changed, then it is a prime
        if (prime[p] == true)
        {
            // Update all multiples of p
            for (int j = p * 2; j <= n; j += p)
                prime[j] = false;
        }
    }

    cout << "Following are the prime numbers smaller than or equal to " << n << '\n';

    // Print all prime numbers
    for (int p = 2; p <= n; p++)
        if (prime[p])
            cout << p << " ";

    return 0;
}

The error is: Unhandled exception at 0x772308F2 in sieve_of_erathosthenes.exe: Microsoft C++ exception: Range_error at memory location 0x004FF670. 错误是: sieve_of_erathosthenes.exe中0x772308F2处未处理的异常:Microsoft C ++异常:内存位置0x004FF670处的Range_error。

I'm a new student and I have difficulties to translate the debugger errors... Thanks, guys! 我是新来的学生,我很难翻译调试器错误...谢谢,伙计们!

In your for loops the termination condition should be p<n because your vector is of size n and vectors are 0-indexed. 在您的for循环中,终止条件应为p<n因为向量的大小为n ,向量的索引为0。

so, accessing prime[n] goes out of range. 因此,访问prime[n]超出范围。 This is the reason for the error. 这就是错误的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM