Clamp funkcija
Napisati funkciju:
template <typename T>
T clamp(const T &value, const T &low, const T &high);koja vraća vrednost value ograničenu donjom i gornjom granicom low i high. Ako je value manje od low, vraća se low. Ako je value veće od high, vraća se high. U suprotnom, vraća se sama vrednost value. Pretpostaviti da tip T podržava operator<.
Test
#include <iostream>
#include <vector>
namespace matf {
template <typename T>
const T& clamp(const T& value, const T& low, const T& high)
{
// Ovde ide vasa implementacija
}
} // namespace matf
int main(void)
{
std::vector<int> test_values = { -10, 0, 5, 10, 15, 20, 30 };
int low = 0;
int high = 20;
for (const auto& val : test_values) {
int clamped_val = matf::clamp(val, low, high);
std::cout << "clamp(" << val << ", " << low << ", " << high << ") = " << clamped_val << std::endl;
}
std::vector<double> test_doubles = { -5.5, 0.0, 2.5, 5.0, 7.5, 10.0, 15.0 };
double dlow = 0.0;
double dhigh = 10.0;
for (const auto& val : test_doubles) {
double clamped_val = matf::clamp(val, dlow, dhigh);
std::cout << "clamp(" << val << ", " << dlow << ", " << dhigh << ") = " << clamped_val << std::endl;
}
std::vector<char> test_chars = { 'a', 'm', 'z', 'A', 'Z' };
char clow = 'f';
char chigh = 'u';
for (const auto& val : test_chars) {
char clamped_val = matf::clamp(val, clow, chigh);
std::cout << "clamp(" << val << ", " << clow << ", " << chigh << ") = " << clamped_val << std::endl;
}
return 0;
}
Rešenje
main.cpp
#include <iostream>
#include <vector>
namespace matf {
template <typename T>
const T& clamp(const T& value, const T& low, const T& high)
{
if (value < low) {
return low;
} else if (value > high) {
return high;
} else {
return value;
}
}
} // namespace matf
int main(void)
{
std::vector<int> test_values = { -10, 0, 5, 10, 15, 20, 30 };
int low = 0;
int high = 20;
for (const auto& val : test_values) {
int clamped_val = matf::clamp(val, low, high);
std::cout << "clamp(" << val << ", " << low << ", " << high << ") = " << clamped_val << std::endl;
}
std::vector<double> test_doubles = { -5.5, 0.0, 2.5, 5.0, 7.5, 10.0, 15.0 };
double dlow = 0.0;
double dhigh = 10.0;
for (const auto& val : test_doubles) {
double clamped_val = matf::clamp(val, dlow, dhigh);
std::cout << "clamp(" << val << ", " << dlow << ", " << dhigh << ") = " << clamped_val << std::endl;
}
std::vector<char> test_chars = { 'a', 'm', 'z', 'A', 'Z' };
char clow = 'f';
char chigh = 'u';
for (const auto& val : test_chars) {
char clamped_val = matf::clamp(val, clow, chigh);
std::cout << "clamp(" << val << ", " << clow << ", " << chigh << ") = " << clamped_val << std::endl;
}
return 0;
}