向量不推送整数

MLA*_*LAC 1 c++ vector

我写了一个简单的程序来生成素数.素数印得很好.我还尝试将每个素数放在一个向量中以便进一步处理,但不知何故,数字似乎没有进入(即push_back)向量,因为它打印出奇怪的数字而不是素数.简而言之,整个程序工作正常,只有向量有问题.请帮忙.

#include <iostream>
#include <iomanip>
#include <vector>

using namespace std;

const int NUM = 300;

int main()
{
    int i, j ;
    int counter = 0;
    bool arr[NUM] = {false}; //false == 0
    vector<int> aVector;

    ...


    cout << "\nNumber of prime numbers is " << counter << endl;

    for (j=0; j<aVector.size() ; j++)
    {
        cout << "aVector[" << j << "] is " << aVector[j] << endl;
    }

   return 0;
}
Run Code Online (Sandbox Code Playgroud)

M.M*_*M.M 6

您的代码访问超出范围arr.数组在C++中是零索引的.

for (i = 2; i<=NUM; i++) 应该: for (i = 2; i<NUM; i++)

for (j = 1; j <= NUM/i; j++) 应该: for (j = 1; j * i < NUM; j++)

应用这些修补程序后,您的代码似乎适合我.我删除了if (i支票,因为它是多余的.

  • @MLAC使用确切的代码(包括我的修复程序)更新您的问题,这显然不起作用.确保您确认运行在问题中发布的*exact*代码会导致问题.我之前看到你匆匆编辑了. (2认同)