簡體   English   中英

c ++數組無法獲得正確的數組

[英]c++ array can't get the right array

我有數組A[9]= {1,2,3,4,5,6,7,8,9}我需要刪除不除以2的數字。我試圖做的代碼:

int main()
{
    int n;
    ifstream fd(Cdf);
    fd>>n; // read how many numbers are in the file.
    int A[n];
    for(int i = 0; i < n; i++)
    {
        fd >> A[i]; //read the numbers from file
    }
    for(int i = 0; i < n; i ++) // moving the numbers.
    {
        if(A[i] % 2 !=0)
        {
            for(int j = i; j < n; j++)
            {
                A[i] = A[i+1];
            }
        }
    }
    fd.close();
    return 0;
}

但我得到像224466888這樣的224466888 我需要做什么來獲得2,4,6,8?

我需要刪除同一個數組中的數字。

首先,您應該將std :: vector用於動態大小的數組。 其次,要刪除偶數在向量中的數字,您可以:

std::vector<int> inf = {12,0,5,6,8};
auto func = [](int i){return i % 2 != 0;}; 
inf.erase(std::remove_if(inf.begin(),inf.end(),func), inf.end());

編輯:

好的,所以你仍然可以在沒有std :: vectors的情況下做到這一點,但它會更加丑陋:

#include <algorithm>

int res[] = {2,5,9,8,6,7};
int size = 6;
auto func = [](int i){return i % 2 != 0;};
int new_size = std::remove_if(res,res + size, func) - res;

你想要的所有數據都在[0,new_size [范圍內,你的數組的另一部分現在是垃圾。

數組不能用於您的目的。 它在堆棧上分配,其大小不能動態更改(通常不能更改數組的大小,不僅在堆棧上分配時)。

您可以分配第二個數組,並在每次添加新元素時使用realloc重新分配它,但這不是執行此操作的好方法。 您正在使用C ++,所以只需使用std::vector<int> ,您的問題就會得到解決:

std::vector<int> evenArray;
evenArray.reserve(sizeof(A)/sizeof(A[0])/2);

if (number is even) {
  evenArray.pushBack(number);
}

請注意,矢量連續存儲元素,因此這是合法的:

int *evenA = &evenArray[0];

對於你的內部for循環,你應該引用j ,而不是i

for(int j = i; j < n - 1; j++)
{
    A[j] = A[j+1];
}

否則,創建j的重點是什么?

當然,這也意味着如果你讀回整個數組,你將顯示所有被移位的字符(這將等於最后一個數字)。 所以,你應該跟蹤數組的新長度,然后迭代到那個而不是數組的末尾。

編輯:
在內部for循環中,你需要循環到n - 1否則當你有A[j + 1]它會在你改變它時離開數組的末尾,這可能會或可能不會給你一個運行時錯誤。

您的刪除循環使用錯誤的變量進行索引:

for(int j = i; j < n; j++)
{
    A[i] = A[i+1];
}

你正在使用i ,它在循環中不會改變。
將其更改為j 您還需要從上限中減去一個,因為當您訪問A[j + 1]時,您將走出數組。

for(int j = i; j < n - 1; j++)
{
    A[j] = A[j + 1];
}

暫無
暫無

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

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