Parnost i deljivost
Napisati funktore is_even is_odd, i is_divisible_by koji proveravaju da li je broj paran, neparan, odnosno deljiv sa zadatim brojem.
Test
#include <iostream>
#include <vector>
namespace matf {
template <typename ForwardIt, typename UnaryPredicate>
size_t count_if(ForwardIt first, ForwardIt last, UnaryPredicate p)
{
size_t count = 0;
for (ForwardIt it = first; it != last; ++it) {
if (p(*it)) {
++count;
}
}
return count;
}
// Ovde idu vase implementacije
} // namespace matf
int main(void)
{
std::vector<int> vec = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
size_t even_count = matf::count_if(vec.begin(), vec.end(), matf::is_even());
std::cout << "Number of even elements: " << even_count << std::endl;
size_t odd_count = matf::count_if(vec.begin(), vec.end(), matf::is_odd());
std::cout << "Number of odd elements: " << odd_count << std::endl;
size_t divisible_by_3_count = matf::count_if(
vec.begin(), vec.end(),
matf::is_divisible_by(3)
);
std::cout << "Number of elements divisible by 3: " << divisible_by_3_count << std::endl;
return 0;
}Rešenje
main.cpp
#include <iostream>
#include <vector>
namespace matf {
template <typename ForwardIt, typename UnaryPredicate>
size_t count_if(ForwardIt first, ForwardIt last, UnaryPredicate p)
{
size_t count = 0;
for (ForwardIt it = first; it != last; ++it) {
if (p(*it)) {
++count;
}
}
return count;
}
struct is_even {
bool operator()(int value) const
{
return value % 2 == 0;
}
};
struct is_odd {
bool operator()(int value) const
{
return value % 2 != 0;
}
};
struct is_divisible_by {
int divisor;
is_divisible_by(int _divisor) : divisor(_divisor) {}
bool operator()(int value) const
{
return value % divisor == 0;
}
};
} // namespace matf
int main(void)
{
std::vector<int> vec = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
size_t even_count = matf::count_if(vec.begin(), vec.end(), matf::is_even());
std::cout << "Number of even elements: " << even_count << std::endl;
size_t odd_count = matf::count_if(vec.begin(), vec.end(), matf::is_odd());
std::cout << "Number of odd elements: " << odd_count << std::endl;
size_t divisible_by_3_count = matf::count_if(
vec.begin(), vec.end(),
matf::is_divisible_by(3)
);
std::cout << "Number of elements divisible by 3: " << divisible_by_3_count << std::endl;
return 0;
}