Inicijalizuj opseg!
Napisati funkciju:
template <typename It, typename T>
void initialize_range(It begin, It end, const T &value);koja inicijalizuje sve elemente u opsegu [begin, end) na vrednost value.
Test
#include <iostream>
#include <vector>
namespace matf {
template <typename ForwardIt, typename T>
void initialize_range(ForwardIt first, ForwardIt last, const T &value)
{
// Ovde ide vasa implementacija
}
} // namespace matf
int main(void)
{
std::vector<int> vec(10);
matf::initialize_range(vec.begin(), vec.end(), 42);
for (const auto &val : vec) {
std::cout << val << " "; // Ispisuje: 42 42 42 42 42 42 42 42 42 42
}
std::cout << std::endl;
std::vector<std::string> str_vec(5);
matf::initialize_range(str_vec.begin(), str_vec.end(), "Hello");
for (const auto &str : str_vec) {
std::cout << str << " "; // Ispisuje: Hello Hello Hello Hello Hello
}
std::cout << std::endl;
return 0;
}Rešenje
main.cpp
#include <iostream>
#include <vector>
namespace matf {
template <typename ForwardIt, typename T>
void initialize_range(ForwardIt first, ForwardIt last, const T &value)
{
for (ForwardIt it = first; it != last; ++it) {
*it = value;
}
}
} // namespace matf
int main(void)
{
std::vector<int> vec(10);
matf::initialize_range(vec.begin(), vec.end(), 42);
for (const auto &val : vec) {
std::cout << val << " "; // Ispisuje: 42 42 42 42 42 42 42 42 42 42
}
std::cout << std::endl;
std::vector<std::string> str_vec(5);
matf::initialize_range(str_vec.begin(), str_vec.end(), "Hello");
for (const auto &str : str_vec) {
std::cout << str << " "; // Ispisuje: Hello Hello Hello Hello Hello
}
std::cout << std::endl;
return 0;
}