创建一个新数组,该数组包含原始数组中位于第一个负元素之前的所有元素
Creating a new array containing all the elements of the original array that are located before the first negative element
这就是我想要的:基于原始数组,创建一个新数组,包含原始数组中位于第一个负元素之前的所有元素。这是我的代码:
#include <iostream>
#include <ctime>
#include <cmath>
#include <iomanip>
#include <vector>
using namespace std;
int main() {
const int N = 1000;
int a[N];
int k;
bool f = false;
vector<int> b;
cout << "Input size of array: ";
cin >> k;
cout << "Input elements: ";
for (int i = 0; i < k; i++) cin >> a[i];
cout << endl;
for (int i = 0; i < k; i++)
{
if (a[i] < 0 && !f)
{
f = true;
}
if (f) b.push_back(a[i]);
}
if (!f) cout << "No negative n >> ";
else for (int i = 0; i < b.size(); i++) cout << b[i] << " ";
cin.get();
return 0;
}
我输出ARTER的第一个负片,但需要BEFORE的第一个负片。
这里使用f
作为一个最初为false的标志。这意味着你还没有得到任何否定。当f
为真时,你可以说你至少得到了一个负数,因为f为真,你不会进一步推任何元素。
所以,你应该推动向量,直到你得到至少1个负数。这意味着只有当flag为false时,你才必须按下。
所以你的推送声明应该是这样的:
if (!f) b.push_back(a[i]);
相关文章:
- 数组元素打印的递归方法
- 如何将字节数组元素替换为修改的十六进制 ASCII 符号?
- 为什么使用数组元素查找最大数字的程序不起作用?
- 数组元素更改值?
- 如何访问宏中定义的数组元素
- 将数组元素递增 1
- C++函数,它将数组、谓词和运算符作为参数,并将运算符应用于满足谓词的数组元素
- 存储指向动态数组元素的指针
- C++通过别名指针以静默方式将错误的类型分配给数组元素
- 在 std::map 中插入数组元素
- 使用指针访问数组元素时出现意外结果
- c++ 使用动态分配运算符反向数组元素
- 为什么在 c++ 中分配 char 数组元素时,分配的字符会被销毁?
- 缺少数组元素问题
- 如何在类中制作 2D 数组元素,然后在其构造函数中指定其维度?
- 创建一个函数来转换数组元素的类型并返回数组的地址
- 删除在结构 c++ 中声明的数组元素
- Getter 和 Setter 用于类 C++ 中的数组元素
- 尝试递归获取数组元素的总和
- 使用SWIG将numpy数组元素(int)传递给c++int