I received a message from HackerRank to solve the Vector-Sort challenge. The requirements call to instantiate a vector of the desired size. Populate and then sort the vector. Once sorted the values in the vector need to be displayed.
Following is a screen capture of a console using the data for sample case:
5 1 6 10 8 4 1 4 6 8 10
Following is my solution written in C++ using Visual Studio 2017 Enterprise Edition:
#include <iostream> #include <vector> #include <algorithm> using namespace std; /* * Test code. */ int main() { // **** **** int N = 0; // **** read N (number of entries for the vector) **** cin >> N; // **** allocate the vector **** vector<int> v(N); // **** populate the vector **** for (int n = 0; n < N; n++) { cin >> v[n]; } // **** sort the vector **** sort(v.begin(), v.end()); // **** display the sorted contents of the vector **** for (int i = 0; i < (int)v.size(); i++) { cout << v[i] << " "; } cout << endl; // **** **** return 0; }
The above code passed the eight test cases.
If you have comments or questions, please leave me a message in the section after this post.
Enjoy;
John
Follow me on Twitter: @john_canessa