Uslovni brojač

Napisati funkciju:

template <typename InputIt, typename UnaryPredicate>
size_t count_if(InputIt first, InputIt last, UnaryPredicate p);

koja vraća broj elemenata u opsegu [first, last) za koje važi predikat p.

Test

#include <iostream>
#include <vector>

namespace matf {

	template <typename InputIt, typename UnaryPredicate>
	size_t count_if(InputIt first, InputIt last, UnaryPredicate p)
	{
        // Ovde ide vasa implementacija
	}

} // 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(),
		[](int x) { return x % 2 == 0; }
	);
	std::cout << "Number of even elements: " << even_count << std::endl; // Output: 5

	size_t greater_then_3 = matf::count_if(
		vec.begin(), vec.end(),
		[](int x) { return x > 3; }
	);
	std::cout << "Number of elements greater than 3: " << greater_then_3 << std::endl; // Output: 7 

	return 0;
}

Rešenje

main.cpp

#include <iostream>
#include <vector>

namespace matf {

	template <typename InputIt, typename UnaryPredicate>
	size_t count_if(InputIt first, InputIt last, UnaryPredicate p)
	{
		size_t count = 0;
		for (InputIt it = first; it != last; ++it) {
			if (p(*it)) {
				++count;
			}
		}
		return count;
	}

} // 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(),
		[](int x) { return x % 2 == 0; }
	);
	std::cout << "Number of even elements: " << even_count << std::endl; // Output: 5

	size_t greater_then_3 = matf::count_if(
		vec.begin(), vec.end(),
		[](int x) { return x > 3; }
	);
	std::cout << "Number of elements greater than 3: " << greater_then_3 << std::endl; // Output: 7 

	return 0;
}