3/01/2018

Day 21 Generics HackerRank Solution In C++

Problem:- Day 21 Generics hacker rank solution or HackerRank-30-Days-of-Code/Day 21 Generics or Day 21 Generics/HackerRank-30-Days-of-Code or Day 21 Generics 30 Days of Code solution or Generics HackerRank solution in c or HackerRank Generics solution in c or Generics solution hacker rank or Generics solution hacker rank in c++ or Generics solution in c++ hacker rank or Day 21: Generics | HACKER RANK SOLUTIONS or Hackerrank Day 21: Generics.

Task:- Write a single generic function named printArray; this function must take an array of generic elements as a parameter (the exception to this is C++, which takes a vector). The locked Solution class in your editor tests your function.

Note: You must use generics to solve this challenge. Do not write overloaded functions.

Input Format

The locked Solution class in your editor will pass different types of arrays to your printArray function.

Constraints

You must have exactly 1 function named printArray.

Output Format

Your printArray function should print each element of its generic array parameter on a new line.

Explanation:- We have to just print the generic array, we can do this by using the AUTO keyword in our program. I didn't understand why people don't use AUTO Keyword in C++. as you can see that generic array means all type of data type in an array so for that this is a best practice to use the AUTO keyword in the problem.

Copy the colored code and paste it into Hacker rank editor and click to submit button, but before this process, you have to click the below link, this link takes to you same problem Now you have to just Login if you are already not log in and done. 

Submit this solution:- Click Here

Solution:-

#include <iostream>
#include <vector>
#include <string>

using namespace std;

template <class T> 
    void printArray(vector<T> i) 

    for(int j=0;j<i.size();j++) 
        cout<<i[j]<<endl;



void printArray(vector<auto> a)
{
    for(auto i:a)
        cout<<i<<endl;
}


int main() {
int n;

cin >> n;
vector<int> int_vector(n);
for (int i = 0; i < n; i++) {
int value;
cin >> value;
int_vector[i] = value;
}

cin >> n;
vector<string> string_vector(n);
for (int i = 0; i < n; i++) {
string value;
cin >> value;
string_vector[i] = value;
}

printArray<int>(int_vector);
printArray<string>(string_vector);

return 0;
}

Output:-

Day 21 Generics HackerRank Solution output


You May Also See

1. Day 22: Binary Search Trees

2. Day 23: BST Level-Order Traversal

3. Day 24: More Linked Lists

4. Day 25: Running Time and Complexity

5. Day 26: Nested Logic

No comments:

Post a Comment