Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use std::minmax_element in a member initializer list?

Tags:

c++

c++11

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.

like image 774
Tim Avatar asked Jan 28 '23 12:01

Tim


1 Answers

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)
    {}

};
like image 199
Jarod42 Avatar answered Feb 01 '23 09:02

Jarod42