簡體   English   中英

向量不push_back整數

[英]The vector doesn't push_back the integer

我寫了一個簡單的程序來生成質數。 質數很好地打印出來。 我還嘗試將每個質數放入向量中以進行進一步處理,但是由於它打印出了奇數而不是質數,所以這些數字似乎並沒有加入向量中(即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檢查了是否多余。

正如MM所指出的那樣,在代碼中的許多地方,您都試圖從arr數組的邊界之外獲取和設置值。 這是C ++中未定義的行為。 一旦調用了未定義的行為, 任何事情都可能發生- 整個程序的行為(不僅是包含錯誤的行)是無法預測的。 在靜態數組邊界之外進行寫入通常會導致覆蓋其他變量。

看起來您的程序將覆蓋aVector的內部數據, aVector用其他方式將其指針替換為動態分配的數組。 難怪它不會打印“隨機垃圾”-向量現在認為它的內容在內存中的其他位置。

根據經驗: 簡單的C []數組是邪惡的 ,請改為使用vectors:
vector<bool> arr(NUM, false) 要訪問元素,請使用: arr.at(some_index) 如果some_index在向量邊界之外,則將引發異常。 請注意,即使您使用向量, arr[some_index]也不執行邊界檢查,因此也可能導致未定義的行為。

這是一個簡單的快速修復。 循環到向量的末尾。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM