array and vector - whitespace

Hello, I am doing problems on hackerrank, and had a question that involved putting values into an array or a vector. I have managed to get this to work but wondering how exactly it does work.

So the input is given as one line input, ie - 1 3 5 7 and each of those ints need to be a different element in the array or the vector, as seen in my code below I done this with a loop, but I am wondering exactly how this works, when the whitespace is read, does the array/vector just know to move passed and ignore it?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
  #include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;


int main() {
    
    int numElements{};
    cin >> numElements;
    vector<int> v;
    int *arr = new int[numElements];
    int input;
    
    for (int i = 0; i < numElements; i++)
    {
        cin >> input;
        //v.push_back(input);
        arr[i] = input;
    }    
    
    
    for (int i = numElements - 1; i >= 0; i--)
    {
      //  cout << "Element stored at " << i << " is : " << arr[i] <<"\n";
        cout << arr[i] << " ";
    }
    
    
    return 0;
}
The vector doesn't do anything. The std::istream (cin)'s operator >> is what does the magic. It parses the input delimited by whitespace, and puts the extracted value into your int input.

Internally, there are probably different possible implementations for operator >>, but it probably just looks at each character until it finds a character matching std::isspace, and then converts the digits into an int (like stoi or atoi).
Last edited on
Thank you, now that you mention istream, i do remember reading something about that back when i started learning. I guess i will need to go back over it :) thanks again
The program has a memory leak - the allocated memory is not released.

As L31

 
delete [] arr;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
#include <vector>

int main()
{
   std::cout << "# of integers to enter: ";
   int num_ints { };
   std::cin >> num_ints;

   // create a vector of known size, zero initialized
   std::vector<int> vec(num_ints);

   for(int i { }; i < num_ints; ++i)
   {
      int num { };
      std::cin >> num;

      vec[i] = num;
   }
   std::cout << '\n';

   std::cout << "The entered numbers are:\n";
   for (const auto& itr : vec)
   {
      std::cout << itr << ' ';
   }
   std::cout << '\n';
}
To reverse access a vector's elements using iterators:
22
23
24
25
26
27
   std::cout << "The entered numbers are:\n";
   for (auto itr { vec.crbegin()}; itr != vec.crend(); ++itr)
   {
      std::cout << *itr << ' ';
   }
   std::cout << '\n';
Topic archived. No new replies allowed.