繁体   English   中英

在x / y坐标可互换的二维矩阵中存储数据

[英]Storing data in a 2d matrix with interchangeable x/y coordinates

我有一个C ++中的节点列表,我希望以某种数据结构dist存储每对节点之间的距离

例如5个节点:(0、1、2、3、4)

我想存储它们之间的距离。 我可以将它们存储在2D矩阵中,但是随后我存储了冗余数据。

存储节点1和3之间距离的dist[1][3]dist[3][1]值相同

此外,不需要dist[0][0]dist[1][1]dist[2][2]等都浪费数据。

我考虑了带有映射功能的一维数组,该函数将[x] [y]坐标映射到数组索引,但是在重新访问代码时可能难以阅读和理解。

在C ++中,像这样在任意排序的索引之间存储某些值的好方法是什么?

正确的抽象是一个class ,它为您包装了数据访问权限。

#include <algorithm>
#include <array>

template <typename TNumber, std::size_t Dimension>
class triangular_matrix
{
public:
    // It's common/friendly to make a value_type for containers
    using value_type = TNumber;

    // Overloading operator() is fairly common and looks pretty decent
    value_type operator()(std::size_t row, std::size_t col) const
    {
        return _data.at(index_of(row, col));
    }

    // A non-const overload allows users to edit using regular assignment (=)
    value_type& operator()(std::size_t row, std::size_t col)
    {
        return _data.at(index_of(row, col));
    }

private:
    // You're storing 1 less than the dimensions
    static constexpr stored_dim = Dimension - 1;

    // Use sum of arithmetic series:
    static constexpr data_size = stored_dim / 2U;

    static std::size_t index_of(std::size_t row, std::size_t col)
    {
        // I'm not sure what you want to do for this case -- you said these
        // indexes aren't needed, but I don't know if you mean they won't be
        // accessed or what...so just throw!
        if (row == col)
            throw std::invalid_argument("row and column can't be the same!");

        // flip
        if (row > col)
            std::swap(row, col);

        // This is probably not the fastest way to do this...
        --row;
        std::size_t index = 0U;
        for (; row > 0U; --row)
            index += row;
        return index + col;
    }

    // Store using a flat array
    std::array<TNumber, data_size> _data;
};

用法如下所示:

triangular_matrix<double, 4> m;
m(1, 3) = 5.2;
m(2, 1) = 9.1;
assert(m(2, 1) == m(1, 2));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM