C++ 17 has std::clamp
。在这种情况下也不需要参数height
和width
。只要运营商<
定义
void clamp_vec(std::vector<double>& input_image, double min_value, double max_value) {
std::transform(std::begin(input_image), std::end(input_image), std::begin(input_image),
[=] (auto i) { return std::clamp(i, min_value, max_value); });
}
模板版本的泛型类型将工作:
template <typename T>
void clamp_vec(std::vector<T>& input_image, const T& min_value, const T& max_value) {
std::transform(std::begin(input_image), std::end(input_image), std::begin(input_image),
[&] (const T& v) { return std::clamp(v, min_value, max_value); });
}
如果std::clamp
不可用,你可以实现你自己的,直到C++ 17恶有恶报,例如:
template <typename T>
constexpr const T& clamp(const T& v, const T& lo, const T& hi) {
return clamp(v, lo, hi, std::less<>());
}
template <typename T, typename Compare>
constexpr const T& clamp(const T& v, const T& lo, const T& hi, Compare comp) {
return comp(v, lo) ? lo : comp(hi, v) ? hi : v;
}
['std :: transform'](http://en.cppreference.com/w/cpp/algorithm/transform)如何使用简单的lambda?由于您无论如何遍历向量的所有元素,实际上并不需要'width'和'height'参数。 –
如果你可以在C++ 17中做到这一点,尝试对值使用['std :: clamp'](http://en.cppreference.com/w/cpp/algorithm/clamp),而不是拼写它与最小和最大。它更具可读性。如果你不能,那就使用你自己的钳模板。 – StoryTeller
@StoryTeller嘿谢谢我现在不能使用c + + 17。谢谢 – Gilad