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;
}
Comments
Dear Lee, there is no 182 lines in this code here.
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