Answer the question
In order to leave comments, you need to log in
Array or vector?
Task about the 27th number from the exam. As you know, some problems ask you to write the most efficient program in terms of time and memory. In this regard, the question arose, which is better to use, a vector or an array?
Here is a brief formulation of one of the tasks: first, N is entered - the number of elements of the numerical sequence, N<100. Then the sequence is entered. At the output, the program should print negative numbers first in the order in which they were given, then positive numbers in the same order. I am attaching the code with an array and a vector.
Code with vector:
#include <iostream>
#include <vector>
using namespace std;
int main() {
unsigned short int n;
cin >> n;
vector <short int> arr;
for (int i = 0; i < n; i++)
{
int k;
cin >> k;
arr.push_back(k);
}
arr.shrink_to_fit();
for (int i = 0; i < n; i++)
{
if (arr[i] < 0)
cout << arr[i] << " ";
}
cout << endl;
for (int i = 0; i < n; i++)
{
if (arr[i] >= 0)
cout << arr[i] << " ";
}
}
#include <iostream>
#include <ctime>
#include <vector>
using namespace std;
int main() {
unsigned short int n;
cin >> n;
short int arr[n];
for (int i = 0; i < n; i++)
{
int k;
cin >> k;
arr[i] = k;
}
for (int i = 0; i < n; i++)
{
if (arr[i] < 0)
cout << arr[i] << " ";
}
cout << endl;
for (int i = 0; i < n; i++)
{
if (arr[i] >= 0)
cout << arr[i] << " ";
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question