向量不push_back整数

The vector doesn't push_back the integer

本文关键字:back 整数 push 向量      更新时间:2023-10-16

我写了一个简单的程序来生成素数。质数打印出来很好。我还试图将每个素数放入一个向量中进行进一步处理,但不知怎的,这些数字似乎没有进入(即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;
}

您的代码访问超出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检查,因为它是多余的。

正如M.M指出的那样,在代码中的许多地方,您试图从arr数组的边界外获取和设置值。这是c++中未定义的行为。一旦调用未定义的行为,任何都可能发生——整个程序的行为(不仅仅是包含错误的行)是不可预测的。在静态数组的边界外写入通常会导致覆盖其他变量。

看起来你的程序覆盖了aVector的内部数据,用其他东西替换了它的指针一个动态分配的数组。难怪它会输出"随机垃圾"——vector现在认为它的内容在内存中的不同位置。

作为经验法则:简单的C[]数组是邪恶的,使用向量代替:
vector<bool> arr(NUM, false)。访问一个元素使用:arr.at(some_index)。如果some_index在向量边界之外,这将抛出异常。注意,arr[some_index]不执行边界检查,即使你使用向量,因此也可能导致未定义的行为。

这是一个简单的快速修复。循环到vector的末尾。

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

------------------------ 完整的代码,我试着

#include <iostream>
#include <vector>
#include <stdio.h>
#include <stdlib.h>
#include <iomanip>
using namespace std;
#define NUM 100
int main()
{
    int i, j ;
    int counter = 0;
    bool arr[NUM] = {false}; //false == 1
    vector<int> aVector;
    for (i = 2; i<=NUM; i++)
    {
        if (arr[i] == 0)
        {
            cout << setw(6) << i ; //i is a prime number
            /****doesn't seem to work****/
            aVector.push_back(i);  //fill the vector with prime numbers
            counter++;
            if (i <= NUM/2)
            {
                for (j = 1; j <= NUM/i; j++)
                {
                    arr[i*j] = 1;
                }
            }
        }
    }
    cout << "nNumber of prime numbers is " << counter << endl;
    /*** it prints out strange numbers ******/
    for (j=0; j<aVector.size() && j < 6 ; j++){
        cout << "aVector[" << j << "] is " << aVector.at(j) << endl;
    }
    return 0;
}