c++ - 埃拉托色尼筛法 C++ - 内存中的范围错误

标签 c++ vector primes sieve-of-eratosthenes

我正在编写这个使用 Sieve 的简单代码,但是有一个错误使程序无法编译。下面是代码:

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

错误是:sieve_of_erathosthenes.exe 中 0x772308F2 处的未处理异常:Microsoft C++ 异常:内存位置 0x004FF670 处的 Range_error。

我是一名新生,我很难翻译调试器错误... 谢谢,伙计们!

最佳答案

在你的for循环终止条件应该是p<n因为你的 vector 大小为 n和 vector 是 0 索引的。

所以,访问 prime[n]超出范围。这就是错误的原因。

关于c++ - 埃拉托色尼筛法 C++ - 内存中的范围错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49600194/

相关文章:

C++,向后读取串行输出文本文件

c++ - 为什么 SHGetFolderPath() 会发生内存泄漏? (C++)

c++ - 使用 RTTI 从实现接口(interface) c++ 的对象中获取类名

c++ - 错误 : use of undeclared identifier 'std' c++

c++ - 字符串 vector 排序

JAVA程序求最大质因数,但输出错误?

c++ - 使用 STL vector 创建矩阵

c++ - 检查 vector<vector<queue<msg>>> 中的 vector 'space' 是否为空

primes - 对于负数, bool 值 isPrime() 应该返回什么?

python - 生成一个比列表中找到的数字大的素数