This is a class that contains a const std::vector
and stores its min and max:
#include <vector>
#include <algorithm>
class MyClass {
public:
const std::vector<int> v;
const std::pair<int, int> minmax_v;
MyClass(const std::vector<int> & v_init)
: v(v_init),
minmax_v(*(std::min_element(v.begin(), v.end())), *(std::max_element(v.begin(), v.end()))) {}
};
It is possible to somehow use std::minmax_element
to initialize minmax_v
? The idea is is to improve performance.
Of course, one could use std::minmax_element
in the constructor body and drop the const
for minmax_v
but that doesn’t feel right either.
Use a delegating constructor to obtain the pair of minmax_element()
results in a single argument:
class MyClass {
public:
const std::vector<int> v;
const std::pair<int, int> minmax_v;
MyClass(const std::vector<int> & v_init)
: MyClass(v_init, std::minmax_element(v_init.begin(), v_init.end()))
{}
private:
MyClass(const std::vector<int> & v_init,
std::pair<std::vector<int>::const_iterator,
std::vector<int>::const_iterator> p)
: v(v_init), minmax_v(*p.first, *p.second)
{}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With