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

Question #76524
Write a function reverse, that takes in a vector<T> and reverses the vector, i.e. modifies the input vector.

#include <vector>

using namespace std;

template <typename T>

void reverse(vector<T> v) {

//code..

}
1
Expert's answer
2018-04-25T08:59:43-0400


Using STL algorithms

#include <vector>
#include <algorithm>

using namespace std;

template <typename T>
void reverse(vector<T>& vec)
{
reverse(vec.begin(), vec.end());
}

int main()
{
vector<int> vec {1,2,3,4,5,6,7};
reverse(vec);

return 0;
}



Using iterators

#include <vector>

using namespace std;

template <typename T>
void reverse(vector<T>& vec)
{
auto beginIt = vec.begin();
auto endIt = --vec.end();
for(; beginIt < endIt; ++beginIt, --endIt)
{
T tmp = *beginIt;
*beginIt = *endIt;
*endIt = tmp;
}
}

int main()
{
vector<int> vec {1,2,3,4,5,6,7,8};
reverse(vec);

return 0;
}

Using iterator and std::swap

#include <vector>
#include <memory>

using namespace std;

template <typename T>
void reverse(vector<T>& vec)
{
auto beginIt = vec.begin();
auto endIt = --vec.end();
for (; beginIt < endIt; ++beginIt, --endIt)
{
std::swap(*beginIt, *endIt);
}
}

int main()
{
vector<int> vec{ 1,2,3,4,5,6,7 };
reverse(vec);

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
26.04.18, 21:22

Dear Lee, there is no 182 lines in this code here.

LEE JIA WEI
26.04.18, 16:45

try using Using iterator and std::swap error code shown: answer.cc:182:31: error: conversion from 'void' to non-scalar type 'std::vector' requested vector ans = reverse(in); ^

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS