Minimalni i maksimalni element
Napisati funkcije:
template <typename ForwardIt>
ForwardIt min_element(ForwardIt first, ForwardIt last);
template <typename ForwardIt>
ForwardIt max_element(ForwardIt first, ForwardIt last);koje vraćaju iteratore na minimalni i maksimalni element u opsegu [first, last). Pretpostaviti da tip na koji pokazuje iterator podržava operator<.
Test
#include <iostream>
#include <vector>
namespace matf {
template <typename ForwardIt>
ForwardIt min_element(ForwardIt first, ForwardIt last)
{
// Ovde ide vasa implementacija
}
template <typename ForwardIt>
ForwardIt max_element(ForwardIt first, ForwardIt last)
{
// Ovde ide vasa implementacija
}
} // namespace matf
int main(void)
{
std::vector<int> vec = { 3, 1, 4, 1, 5, 9, 2, 6, 5 };
auto min_it = matf::min_element(vec.begin(), vec.end());
auto max_it = matf::max_element(vec.begin(), vec.end());
std::cout << "Min element: " << *min_it << std::endl; // Output: Min element: 1
std::cout << "Max element: " << *max_it << std::endl; // Output: Max element: 9
std::vector<std::string> str_vec = { "cherry", "apple", "banana", "date" };
auto str_min_it = matf::min_element(str_vec.begin(), str_vec.end());
auto str_max_it = matf::max_element(str_vec.begin(), str_vec.end());
std::cout << "Min string: " << *str_min_it << std::endl; // Output: Min string: apple
std::cout << "Max string: " << *str_max_it << std::endl; // Output: Max string: date
return 0;
}Rešenje
main.cpp
#include <iostream>
#include <vector>
namespace matf {
template <typename ForwardIt>
ForwardIt min_element(ForwardIt first, ForwardIt last)
{
if (first == last) {
return last;
}
ForwardIt min_it = first;
for (++first; first != last; ++first) {
if (*first < *min_it) {
min_it = first;
}
}
return min_it;
}
template <typename ForwardIt>
ForwardIt max_element(ForwardIt first, ForwardIt last)
{
if (first == last) {
return last;
}
ForwardIt max_it = first;
for (++first; first != last; ++first) {
if (*max_it < *first) {
max_it = first;
}
}
return max_it;
}
} // namespace matf
int main(void)
{
std::vector<int> vec = { 3, 1, 4, 1, 5, 9, 2, 6, 5 };
auto min_it = matf::min_element(vec.begin(), vec.end());
auto max_it = matf::max_element(vec.begin(), vec.end());
std::cout << "Min element: " << *min_it << std::endl; // Output: Min element: 1
std::cout << "Max element: " << *max_it << std::endl; // Output: Max element: 9
std::vector<std::string> str_vec = { "cherry", "apple", "banana", "date" };
auto str_min_it = matf::min_element(str_vec.begin(), str_vec.end());
auto str_max_it = matf::max_element(str_vec.begin(), str_vec.end());
std::cout << "Min string: " << *str_min_it << std::endl; // Output: Min string: apple
std::cout << "Max string: " << *str_max_it << std::endl; // Output: Max string: date
return 0;
}