63 800
Assignments Done
99,5%
Successfully Done
In August 2018

Answer to Question #76525 in C++ for LEE JIA WEI

Question #76525
Write a function reverse, that takes in a vector<T> and returns a new vector<T> that has the contents reversed.

Try practicing with and without using iterators.

#include <vector>

using namespace std;


vector<T> reverse(vector<T> v) {
//code
}
Expert's answer
#include <iostream>
#include <vector>
#include <iterator>

using namespace std;

// function reverse without iterators
template <typename T>
vector<T> reverse1(vector<T> v) {
vector<T> a;
for (int i = v.size()-1; i >= 0; i--)
a.push_back(v[i]);
return a;
}

// function reverse with iterators
template <typename T>
vector<T> reverse2(vector<T> v) {
typename vector<T>::iterator it;
vector<T> a;
for (it = v.end()-1; it>=v.begin(); --it)
a.push_back(*it);
return a;
}

// print vector
template <typename T>
void print (const vector<T> &v) {
for (int i = 0; i < v.size(); i++)
cout << v[i] << " ";
cout << endl;
}

main() {
vector<int> a = {1,2,3,4,5};
vector<string> b = {"aa1","bb2","cc3","dd4","ee5"};

print(a);
vector<int> a1 = reverse1(a);
print(a1);
vector<int> a2 = reverse2(a);
print(a1);

print(b);
vector<string> b1 = reverse1(b);
print(b1);
vector<string> b2 = reverse2(b);
print(b2);

return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

Assignment Expert
28.04.18, 14:41

Dear Lee,
please use panel for submitting new questions

LEE JIA WEI
28.04.18, 13:42

how to modified the code without iterators to run a simulator that default input is
reverse({1, 2, 3, 4, 5})

Leave a comment

Ask Your question

Submit
Privacy policy Terms and Conditions