如何在C ++中存储自定义对象矩阵 [英] How to store a matrix of custom objects in C++

查看:132
本文介绍了如何在C ++中存储自定义对象矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个定义的C ++类,并且想存储该类实例的矩阵.有没有人提供一些代码示例来做到这一点?我找到了带有矢量的示例,但是不确定是否这是最好的解决方案,或者不确定是否有简单"的东西(更像是Objective-C风格-> NSArray * array ).

I have a C++ class that I defined and would like to store a matrix of instances of this class. Has anyone some code samples to do so? I have found examples with vectors but I am not sure if this is the best solution or if there is something "simpler" (more like Objective-C style -> NSArray * array).

有什么建议吗?

推荐答案

在这个宇宙中从来没有最佳解决方案"存在.有很多方法可以用C ++表示矩阵,这取决于您的选择.

There is no never "best solution" exist in this universe. There are plenty of ways to present a matrix in C++ and it's really up to you to choose.

1. C风格的天真解决方案

使用多维数组(静态或动态):

Use multidimensional array (static or dynamic):

MyClass arr[size_y][size_x];

MyClass** arr;

用法:

arr[y][x] = MyClass(a, b, c);  // writing to (x, y)

代码简单,性能低下(引用的局部性),容易发生内存泄漏(手动内存管理)和容易出错(例如访问范围外)

Simple to code, poor performance (locality of references), memory leak prone (manual memory management) and error-prone (such as access out of bounds)

2. C风格的解决方案

使用普通数组而不是多维数组.

Use plain array instead of multidimensional.

  MyClass arr[size_y * size_x];
  arr[y * size_x + x] = MyClass(a, b, c); // writing to (x, y)

缓存友好,更难编写代码,每次计算索引仍然会泄漏和容易出错.

Cache-friendly, lil' bit harder to code, calculating index each time still can leak and error prone .

3. C ++程序样式解决方案

与上述相同,但使用std::array(用于固定大小的矩阵)或std::vector(用于动态大小的矩阵)代替普通数组.

Same as above, but use std::array (for fixed size matrix) or std::vector (for dynamic size matrix) instead of plain arrays.

std::array<MyClass, size_x * size_y> arr;
arr[y * size_x + x] = MyClass(a, b, c); // writing to (x, y)

友好的缓存,没有泄漏,仍然没有限制.

Cache-friendly, no leaks, out of bounds still there.

4.面向对象的C ++解决方案

使用std::array(对于固定大小的矩阵)或std::vector(对于动态大小的矩阵)编写(模板化)类作为基础存储.重载operator().

Write (templated) class with std::array (for fixed size matrix) or std::vector (for dynamic size matrix) as underlying storage. Overload operator().

template<class T, size_t rows, size_t cols>
class Matrix
{
    std::array<T, rows * cols> m_Data;
public:
    T& operator()(size_t y, size_t x)
    {
        return m_Data[y * cols + x];
    }

    // more methods go here
}

用法:

 Matrix<MyClass, size_x, size_y> arr;
 arr(x, y) = MyClass(a, b, c); // writing to (x, y)

缓存友好,无泄漏,程序员友好的语法.聪明的! ;)

Cache-friendly, no leaks, programmer-friendly syntax. Smart! ;)

5.使用一些lib

如果您需要一些线性代数的细节,例如稀疏矩阵,或者只是不想重新发明轮子,请去谷歌搜索一些库.以下是一些示例:提高uBlas 阿玛迪洛

If you need some linear algebra specifics, like sparse matrices, or you just don't want to reinvent the wheel, go and google up some library. Here are some examples: Boost uBlas, Armadillo, Eigen. Smart, convenient, but needs some learning.

这篇关于如何在C ++中存储自定义对象矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆