创建一个新数组,该数组包含原始数组中位于第一个负元素之前的所有元素

Creating a new array containing all the elements of the original array that are located before the first negative element

本文关键字:数组 元素 第一个 包含 新数组 一个 原始 创建      更新时间:2024-09-29

这就是我想要的:基于原始数组,创建一个新数组,包含原始数组中位于第一个负元素之前的所有元素。这是我的代码:

#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]);