c++抛出数组中的每个数字x
c++ throwing every number x from an array
我想制作一个函数,从数组中抛出数字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
相关文章:
- 在将数字随机生成为数组期间从内存输出随机数的数组
- 如何计算数组中元素的位数?(不是数组的长度),并计算其数字的总和
- 数组/c++中的大量数字
- 遍历并行数组以确定C++中的最大数字
- 整数区间(或 int 数组)中每个数字的出现次数
- 如何在 C++ 中将文件中的逗号分隔数字读取到数组中?
- 将随机生成的数字添加到数组 + 对这些数组求平均值
- 遇到此问题时遇到困难:允许用户输入数组的值并使用 for,而循环也输出输入的最大数字
- 获取 2D 数组 c++ 中的所有数字对
- 为什么使用数组元素查找最大数字的程序不起作用?
- 如何从向量或数组中选择最常见的数字?(前五名)C++
- 如何从保存在 Java 中C++的字节数组中读取数字?
- 以十为基数的数字到布尔数组,该数组要求二进制/基数为 2 的数字
- C++ 检查结果数组中有多少次数字
- 如何在不使用 C++ 中的数组或函数的情况下查找 N 位数字的所有排列
- 如何在C++中有效地将数字值重新分配给字符数组
- 查找数组中的最小数字
- 查找数组中重复(重复)数字的索引
- 我必须找到给定数组中所有数字的周期,就像有很多解决方案,但数组的大小是 10^5
- 类、数字/数组或对象中的对象