如何删除小于C 中x的数组中的整数
How to remove integers in array less than X in C++?
我发现了PHP的同样问题,我尝试在C 中进行相同的问题。
我尝试了以下内容:
// returns new array with numbers lower then "number", len is set to
// new length.
int * filter(int array[], int &len, int number) {
int cnt = 0;
for (int i = 0; i < len; i++) {
if (array[i] < number) {
cnt++;
}
}
int *ret = new int[cnt];
cnt = 0;
for (int i = 0; i < len; i++) {
if (array[i] < number) {
ret[cnt] = array[i];
cnt++;
}
}
len = cnt;
return ret;
}
此功能将创建一个新数组,其整数低于整数number
。我试图绕过我不知道新数组应该多长时间的问题。
有什么更好的方法可以解决此问题?
是的,使用std::vector
类型。每次将值推到它时,它都会自动为您处理分配(使用push_back
方法(。
示例
#include <iostream>
#include <vector>
int main() {
std::vector<int> a;
a.push_back(1);
a.push_back(2);
for (int value : a) {
std::cout << value << 'n';
}
}
与std::vector
不同,避免new
语法也是一个好主意。
另外,尽管这与问题无关,但C 提供了一个可以执行您想要的已称为std::copy_if
的函数。
std::remove
是您要寻找的算法。
#include <iterator>
#include <algorithm>
int main()
{
int array[4] = {1, 42, 314, 42};
// If you only know `array` as a pointer, and `len`, then
// `std::begin(array)` becomes `array`, and
// `std::end(array)` becomes `array + len`.
auto end = std::remove(std::begin(array), std::end(array), 42);
// Now `end` points to the "new end" of the array.
// And `std::distance(std::begin(array), end)` is the "new length".
}
它将所有匹配的元素(示例中的42个(移至数组末端。在std::remove
运行后检查array
时,您将获得{1, 314, 42, 42}
,并且end
指向最后一个不匹配元素(在这种情况下为第一个42(。
也可以使用std::remove_copy
或std::copy_if
将非匹配元素复制到另一个数组,但是为了做到这一点,您必须分配另一个元素数组。在这一点上,最好使用动态增长阵列(例如std::vector
(。在这种情况下,使用std::remove
的答案中的std::vector::erase
。
相关文章:
- C++使用整数的压缩数组初始化对象
- 在一定长度后从数组中打印时缺少整数
- 是否基于数组B整数打印数组A中的整数
- 检查TCHAR数组输入是否为带符号整数C++
- 如何将以逗号和空格分隔的整数读取到 2D 数组中?
- 从二进制文件中读取整数数组
- 整数区间(或 int 数组)中每个数字的出现次数
- 新的整数数组向右移动?
- C++ 中的二维整数数组,每行中的元素数量不均匀
- 在数组中输入 n 个整数的列表,并以类似于钟摆来回移动的方式排列它们. 输入-1 3 2 5 4,输出5 3 1 2 4
- 给定一个整数数组,需要在Max_Heap上运行操作。得到错误"segmentation fault",有什么想法吗?(C++)
- 为什么在我的 main 函数中声明整数后我的整数数组中会出现错误?
- 如何将字符串和整数读取到两个单独的动态数组中的程序编写?
- 在 C++ 中将整数数组转换为位集表示形式的最佳方法?
- C++数组输入不接受一定数量的整数
- 从两个 4x64 位整数数组中获取取模
- 如何计算数组整数的总可能组合
- 2D 字符串数组 C++:整数串联成字符串
- 将数组整数2除以偶数和
- 将2d数组整数数据从c++发送到qml