Obrni opseg!
Napisati funkciju:
template <typename BidirectionalIt>
void reverse_range(BidirectionalIt first, BidirectionalIt last);Test
#include <iostream>
#include <vector>
#include <string>
namespace matf {
template <typename BidirectionalIt>
void reverse_range(BidirectionalIt first, BidirectionalIt last)
{
// Ovde ide vasa implementacija
}
}
} // namespace matf
int main(void)
{
std::vector<int> vec = { 1, 2, 3, 4, 5 };
matf::reverse_range(vec.begin(), vec.end());
for (const auto &val : vec) {
std::cout << val << " "; // Ispisuje: 5 4 3 2 1
}
std::cout << std::endl;
std::string str = "Hello, World!";
matf::reverse_range(str.begin(), str.end());
std::cout << str << std::endl; // Ispisuje: !dlroW ,olleH
return 0;
}Rešenje
main.cpp
#include <iostream>
#include <vector>
#include <string>
namespace matf {
template <typename BidirectionalIt>
void reverse_range(BidirectionalIt first, BidirectionalIt last)
{
if (first == last) {
return;
}
--last;
while (first < last) {
std::swap(*first, *last);
++first;
if (first == last) {
break;
}
--last;
}
}
} // namespace matf
int main(void)
{
std::vector<int> vec = { 1, 2, 3, 4, 5 };
matf::reverse_range(vec.begin(), vec.end());
for (const auto &val : vec) {
std::cout << val << " "; // Ispisuje: 5 4 3 2 1
}
std::cout << std::endl;
std::string str = "Hello, World!";
matf::reverse_range(str.begin(), str.end());
std::cout << str << std::endl; // Ispisuje: !dlroW ,olleH
return 0;
}