M
M
Maxim Korytko2019-04-08 20:14:51
Arrays
Maxim Korytko, 2019-04-08 20:14:51

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] << " ";
  }
}

Array code:
#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

1 answer(s)
D
David, 2019-04-09
@rockstardavid

Vectors are allocated on the heap, arrays are on the stack + the vector is dynamically expanded, which introduces an additional overhead. Draw
the conclusion yourself, I recommend reading at least this and this

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question