c++抛出数组中的每个数字x

c++ throwing every number x from an array

本文关键字:数字 数组 c++      更新时间:2023-10-16

我想制作一个函数,从数组中抛出数字x,然后通过对(n)的引用来更新该数组(n)。

例如,我有一个数组a[]=3,4,2,1,4;它的尺寸是5号。如果我选择我的x元素为4,我的数组应该变成3,2,1;它的大小应该是3。

这就是我的函数的外观,它实际上删除了第一个4,但当它找到第二个4时,它会将其更改为0。

void throwOut(int a[], int& n, int x)
{
    int i;
    for ( i = 0; i < n; i++)
    {
        if (a[i] == x)
        {
            for (; i < n - 1; i++)
            {
                a[i] = a[i + 1];
            }
            a[i - 1] = 0;
            n -= 1;
        }
    }
}

普通数组在c++中不能像这样工作。它们具有静态固定的大小。你唯一能做的就是把不必要的元素交换到最后,然后忘记它们。或者更好的是,您可以使用std::vector:

std::vector<int> v = {1, 2, 5, 3, 4, 5, 6, 7, 5, 8};
int to_remove = 5;
// move elems equal to `to_remove` to the end, then remove them from v
v.erase(std::remove(v.begin(), v.end(), to_remove), v.end());
#include <iostream>
#include <string>
int found(int array[], int size, int key);
void throwOut(int array[], int &size, int key);
int main()
{
  int array[] = {8, 4, 2, 8, 0, 3};
  int size = 6;
  int key = 8;
  throwOut(array, size, key);
  for(int i = 0; i < size; i++) {
      std::cout<<array[i]<< " ";
  }
}
// This function found key in array.
// return first index where key was found.
// return -1 if key was not found.
int found(int array[], int size, int key) {
    for (int i = 0; i < size; i++) {
        if (array[i] == key) {
            return i;
        }
    }
    return -1;
}
// This function removes all key from array and then fix the size of array.
void throwOut(int array[], int &size, int key) {
    int f = found(array, size, key);
    if (f >= 0) {
        int count = 1;
        for (int i = f + 1; i < size; i++) {
            if (array[i] != key) {
                array[f] = array[i];
                f++;
            } else {
                count++;
            }
        }
        size -= count;
    }
}

当我运行这个代码时,它会打印4 2 0 3。您也可以在此处运行它:http://cpp.sh/5gqd