Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find max position in a vector of vector of vector

Tags:

c++

vector

I have a vector of vector of vector

std::vector<std::vector<std::vector<double>>> mountain_table

and I would like to find the coordinates i, j, k of this vector for which it is the highest. I know that I should use max_element but I don't know how to use it in a 3d vector.

How should I get those coordinates?

like image 375
Mar Avatar asked Jan 02 '23 21:01

Mar


1 Answers

I'd suggest to linearize your data in order to be able to use standard algorithms. The idea is to provide a couple of functions to get an index from 3D coords and vice et versa:

template<class T>
class Matrix3D // minimal
{
public:
    using value_type = T;
    using iterator   = std::vector<value_type>::iterator;

private:
    std::vector<value_type> _data;
    size_t _sizex, _sizey, _sizez;

    size_t index_from_coords(size_t x, size_t y, size_t z) const
    {
        return x*_sizex*_sizey + y*_sizey + z;
    }
    std::tuple<size_t, size_t, size_t> coords_from_index(size_t index) const
    {
        const size_t x = index / (_sizex * _sizey);
        index = index % x;
        const size_t y = index / _sizey;
        const size_t z = index % _sizey;
        return make_tuple(x, y, z);
    }

public:
    Matrix3D(size_t sizex, sizey, sizez) : _sizex(sizex), ... {}
    T& operator()(size_t x, size_t y, size_t z) // add const version
    {
        return _data[index_from_coords(x, y, z)];
    }
    std::tuple<size_t, size_t, size_t> coords(iterator it)
    {
        size_t index = std::distance(begin(_data), it);
        return coords_from_index(index);
    }
    iterator begin() { return begin(_data); }
    iterator end()   { return end(_data);   }
}

Usage:

Matrix3D<double> m(3, 3, 3);
auto it = std::max_element(m.begin(), m.end()); // or min, or whatever from http://en.cppreference.com/w/cpp/header/algorithm
auto coords = m.coords(it);
std::cout << "x=" << coords.get<0>() << ... << "\n";

This is untested and incomplete code to give you a kickstart into better data design. i'd be happy to answer further questions about this idea in the comment below ;)

like image 89
YSC Avatar answered Jan 15 '23 18:01

YSC