jack06215
3/21/2018 - 12:36 AM

Arrays - DS

Input Format

The first line contains an integer, (the number of integers in ). The second line contains space-separated integers describing .

Constraints

Output Format

Print all integers in in reverse order as a single line of space-separated integers.

Sample Input

4 1 4 3 2 Sample Output

2 3 4 1

#include <bits/stdc++.h>

using namespace std;

vector<string> split_string(string);

int main()
{
    int n;
    
    // read input, then ignore until "newline"
    cin >> n;
    cin.ignore(numeric_limits<streamsize>::max(), '\n');

    // read second line
    string arr_temp_temp;
    getline(cin, arr_temp_temp);

    vector<string> arr_temp = split_string(arr_temp_temp);

    // convert string to int and add to arr[]
    vector<int> arr(n);
    for (int arr_itr = 0; arr_itr < n; arr_itr++) {
        int arr_item = stoi(arr_temp[arr_itr]);
        arr[arr_itr] = arr_item;
    }
    
    reverse(arr.begin(), arr.end());
    for (int i = 0; i < arr.size(); i++)
        cout << arr[i] << ' ';

    return 0;
}

vector<string> split_string(string input_string) {
    string::iterator new_end = unique(input_string.begin(), input_string.end(), [] (const char &x, const char &y) {
        return x == y and x == ' ';
    });

    input_string.erase(new_end, input_string.end());

    // safeguard procedure to remove space in the tail of string.
    while (input_string[input_string.length() - 1] == ' ') {
        input_string.pop_back();
    }

    vector<string> splits;
    char delimiter = ' ';

    // set the first position
    size_t i = 0;
    
    // find the first occuring position of delimiter (' ')
    size_t pos = input_string.find(delimiter);

    while (pos != string::npos) {
        // extract number: start from i position until the delimiter
        splits.push_back(input_string.substr(i, pos - i));
        
        // move the new position to the next number (i.e. right after the delimiter)
        i = pos + 1;
        
        // repeat the same process, but start from position i
        pos = input_string.find(delimiter, i);
    }
    
    // push the last occuring number in the string.
    splits.push_back(input_string.substr(i, min(pos, input_string.length()) - i + 1));

    return splits;
}