nth_element with functor (C++)

nthFunctor.cpp

class comp_with_indirection
{
public:
    explicit comp_with_indirection(const std::vector<float>& floats) :
        floats(floats)
    {}

    bool operator() (int lhs, int rhs) const { return floats[lhs] < floats[rhs]; }

private:
    const std::vector<float>& floats;
};

//use it like
int find_median(const std::vector<float>& v_f, std::vector<int> &v_i)
{
    assert(!v_i.empty());
    assert(v_i.size() <= v_f.size());

    const size_t middle = v_i.size() / 2;
    std::nth_element(v_i.begin(), v_i.begin() + middle, v_i.end(), comp_with_indirection(v_f));
    return v_i[middle];
}

//In C++11, you can use lambda
int find_median(const std::vector<float>& v_f, std::vector<int> &v_i)
{
    assert(!v_i.empty());
    assert(v_i.size() <= v_f.size());

    const size_t middle = v_i.size() / 2;
    std::nth_element(
        v_i.begin(), v_i.begin() + middle, v_i.end(),
        [&v_f](int lhs, int rhs) {
            return v_f[lhs] < v_f[rhs];
        });
    return v_i[middle];
}

This code was an answer to a question by me, Georgios Samaras , in Stackoverflow.

Have questions about this code? Comments? Did you find a bug? Let me know!😀
Page created by G. (George) Samaras (DIT)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s