如何制作“杂色”字体?矢量类 [英] How to make a "variadic" vector like class

查看:85
本文介绍了如何制作“杂色”字体?矢量类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作充当多维向量的类。它不需要做任何花哨的事情。我基本上想拥有一个容器类foo,我可以在其中通过foo [x] [y] [z]访问元素。现在,我还需要foo [x] [y]和foo [x]的类似类。这使我思考以下(更一般的)问题,是否有办法进行这样的事情:您可以针对任意n个参数将其初始化为foo A(a,b,c,...)并获取一个n维向量,其元素可通过[] [] [] ...访问?在类的下面,例如(四维的情况)。

I am trying to make class that acts as multidimensional vector. It doesn't have to do anything fancy. I basically want to have a "container" class foo where I can access elements by foo[x][y][z]. Now I would also need similar classes for foo[x][y] and foo[x]. Which lead me to ponder about the following (more general) question, is there a way to make something like this where you can just initialize as foo A(a,b,c,...) for any n number of arguments and get a n-dimensional vector with elements accessible by [][][]...? Below the class I have for (in example) the four-dimensional case.

首先是标题

   #ifndef FCONTAINER_H
   #define FCONTAINER_H
   #include <iostream>
   using namespace std;

   class Fcontainer
   {
   private:
           unsigned dim1, dim2, dim3, dim4 ;
           double* data;
   public:
           Fcontainer(unsigned const dims1, unsigned const dims2, unsigned const dims3, unsigned const dims4);
           ~Fcontainer();

           Fcontainer(const Fcontainer& m);
           Fcontainer& operator= (const Fcontainer& m);

           double& operator() (unsigned const dim1, unsigned const dim2, unsigned const dim3, unsigned const dim4);
           double const& operator() (unsigned const dim1, unsigned const dim2, unsigned const dim3, unsigned const dim4) const;
    };
    #endif // FCONTAINER_H

现在的cpp:

  #include "fcontainer.hpp"

  Fcontainer::Fcontainer(unsigned const dims1, unsigned const dims2, unsigned const dims3, unsigned const dims4)
  {
       dim1 = dims1; dim2 = dims2; dim3 = dims3; dim4 = dims4;
       if (dims1 == 0 || dims2 == 0 || dims3 == 0 || dims4 == 0)
          throw std::invalid_argument("Container constructor has 0 size");
       data = new double[dims1 * dims2 * dims3 * dims4];
  }

  Fcontainer::~Fcontainer()
  {
      delete[] data;
  }

  double& Fcontainer::operator() (unsigned const dims1, unsigned const dims2, unsigned const dims3, unsigned const dims4)
  {
       if (dims1 >= dim1 || dims2 >= dim2 || dims3 >= dim3 || dims4 >= dim4)
           throw std::invalid_argument("Container subscript out of bounds");
       return data[dims1*dim2*dims3*dim4 + dims2*dim3*dim4 + dim3*dim4 + dims4];
  }

  double const& Fcontainer::operator() (unsigned const dims1, unsigned const dims2, unsigned const dims3, unsigned const dims4) const
  {
     if(dims1 >= dim1 || dims2 >= dim2 || dims3 >= dim3 || dims4 >= dim4)
         throw std::invalid_argument("Container subscript out of bounds");
      return data[dims1*dim2*dims3*dim4 + dims2*dim3*dim4 + dim3*dim4 + dims4];
  }

所以我想将其扩展到任意尺寸。我想这将采用可变参数模板或std :: initializer_list的形式,但是我不清楚如何处理此问题(针对此问题)。

So I want to expand this to an arbitrary amount of dimensions. I suppose it will take something along the lines of a variadic template or an std::initializer_list but I am not clear on how to approach this( for this problem).

推荐答案

在Visual Studio中闲逛了一会儿,我想到了这个废话:

Messing around in Visual Studio for a little while, I came up with this nonsense:

template<typename T>
class Matrix {
    std::vector<size_t> dimensions;
    std::unique_ptr<T[]> _data;

    template<typename ... Dimensions>
    size_t apply_dimensions(size_t dim, Dimensions&& ... dims) {
        dimensions.emplace_back(dim);
        return dim * apply_dimensions(std::forward<Dimensions>(dims)...);
    }

    size_t apply_dimensions(size_t dim) {
        dimensions.emplace_back(dim);
        return dim;
    }
public:
    Matrix(std::vector<size_t> dims) : dimensions(std::move(dims)) {
        size_t size = flat_size();
        _data = std::make_unique<T[]>(size);
    }

    template<typename ... Dimensions>
    Matrix(size_t dim, Dimensions&&... dims) {
        size_t size = apply_dimensions(dim, std::forward<Dimensions>(dims)...);
        _data = std::make_unique<T[]>(size);
    }

    T & operator()(std::vector<size_t> const& indexes) {
        if(indexes.size() != dimensions.size())
            throw std::runtime_error("Incorrect number of parameters used to retrieve Matrix Data!");
        return _data[get_flat_index(indexes)];
    }

    T const& operator()(std::vector<size_t> const& indexes) const {
        if (indexes.size() != dimensions.size())
            throw std::runtime_error("Incorrect number of parameters used to retrieve Matrix Data!");
        return _data[get_flat_index(indexes)];
    }

    template<typename ... Indexes>
    T & operator()(size_t idx, Indexes&& ... indexes) {
        if (sizeof...(indexes)+1 != dimensions.size())
            throw std::runtime_error("Incorrect number of parameters used to retrieve Matrix Data!");
        size_t flat_index = get_flat_index(0, idx, std::forward<Indexes>(indexes)...);
        return at(flat_index);
    }

    template<typename ... Indexes>
    T const& operator()(size_t idx, Indexes&& ... indexes) const {
        if (sizeof...(indexes)+1 != dimensions.size())
            throw std::runtime_error("Incorrect number of parameters used to retrieve Matrix Data!");
        size_t flat_index = get_flat_index(0, idx, std::forward<Indexes>(indexes)...);
        return at(flat_index);
    }

    T & at(size_t flat_index) {
        return _data[flat_index];
    }

    T const& at(size_t flat_index) const {
        return _data[flat_index];
    }

    size_t dimension_size(size_t dim) const {
        return dimensions[dim];
    }

    size_t num_of_dimensions() const {
        return dimensions.size();
    }

    size_t flat_size() const {
        size_t size = 1;
        for (size_t dim : dimensions)
            size *= dim;
        return size;
    }

private:
    size_t get_flat_index(std::vector<size_t> const& indexes) const {
        size_t dim = 0;
        size_t flat_index = 0;
        for (size_t index : indexes) {
            flat_index += get_offset(index, dim++);
        }
        return flat_index;
    }

    template<typename ... Indexes>
    size_t get_flat_index(size_t dim, size_t index, Indexes&& ... indexes) const {
        return get_offset(index, dim) + get_flat_index(dim + 1, std::forward<Indexes>(indexes)...);
    }

    size_t get_flat_index(size_t dim, size_t index) const {
        return get_offset(index, dim);
    }

    size_t get_offset(size_t index, size_t dim) const {
        if (index >= dimensions[dim])
            throw std::runtime_error("Index out of Bounds");
        for (size_t i = dim + 1; i < dimensions.size(); i++) {
            index *= dimensions[i];
        }
        return index;
    }
};

让我们来谈谈这段代码是做什么的。

Let's talk about what this code accomplishes.

//private:
    template<typename ... Dimensions>
    size_t apply_dimensions(size_t dim, Dimensions&& ... dims) {
        dimensions.emplace_back(dim);
        return dim * apply_dimensions(std::forward<Dimensions>(dims)...);
    }

    size_t apply_dimensions(size_t dim) {
        dimensions.emplace_back(dim);
        return dim;
    }
public:
    Matrix(std::vector<size_t> dims) : dimensions(std::move(dims)) {
        size_t size = flat_size();
        _data = std::make_unique<T[]>(size);
    }

    template<typename ... Dimensions>
    Matrix(size_t dim, Dimensions&&... dims) {
        size_t size = apply_dimensions(dim, std::forward<Dimensions>(dims)...);
        _data = std::make_unique<T[]>(size);
    }

此代码使我们能够执行的操作是为该矩阵编写一个初始化器,该初始化器需要任意数量的

What this code enables us to do is write an initializer for this matrix that takes an arbitrary number of dimensions.

int main() {
    Matrix<int> mat{2, 2}; //Yields a 2x2 2D Rectangular Matrix
    mat = Matrix<int>{4, 6, 5};//mat is now a 4x6x5 3D Rectangular Matrix
    mat = Matrix<int>{9};//mat is now a 9-length 1D array.
    mat = Matrix<int>{2, 3, 4, 5, 6, 7, 8, 9};//Why would you do this? (yet it compiles...)
}

如果仅知道尺寸的数量和大小在运行时,此代码将解决以下问题:

And if the number and sizes of the dimensions is only known at runtime, this code will work around that:

int main() {
    std::cout << "Input the sizes of each of the dimensions.\n";
    std::string line;
    std::getline(std::cin, line);
    std::stringstream ss(line);
    size_t dim;
    std::vector<size_t> dimensions;
    while(ss >> dim)
        dimensions.emplace_back(dim);

    Matrix<int> mat{dimensions};//Voila.
}

然后,我们希望能够访问此矩阵的任意索引。这段代码提供了两种方法:静态使用模板,或在运行时可变。

Then, we want to be able to access arbitrary indexes of this matrix. This code offers two ways to do so: either statically using templates, or variably at runtime.

//public:
    T & operator()(std::vector<size_t> const& indexes) {
        if(indexes.size() != dimensions.size())
            throw std::runtime_error("Incorrect number of parameters used to retrieve Matrix Data!");
        return _data[get_flat_index(indexes)];
    }

    T const& operator()(std::vector<size_t> const& indexes) const {
        if (indexes.size() != dimensions.size())
            throw std::runtime_error("Incorrect number of parameters used to retrieve Matrix Data!");
        return _data[get_flat_index(indexes)];
    }

    template<typename ... Indexes>
    T & operator()(size_t idx, Indexes&& ... indexes) {
        if (sizeof...(indexes)+1 != dimensions.size())
            throw std::runtime_error("Incorrect number of parameters used to retrieve Matrix Data!");
        size_t flat_index = get_flat_index(0, idx, std::forward<Indexes>(indexes)...);
        return at(flat_index);
    }

    template<typename ... Indexes>
    T const& operator()(size_t idx, Indexes&& ... indexes) const {
        if (sizeof...(indexes)+1 != dimensions.size())
            throw std::runtime_error("Incorrect number of parameters used to retrieve Matrix Data!");
        size_t flat_index = get_flat_index(0, idx, std::forward<Indexes>(indexes)...);
        return at(flat_index);
    }

然后,在实践中:

Matrix<int> mat{6, 5};
mat(5, 2) = 17;
//mat(5, 1, 7) = 24; //throws exception at runtime because of wrong number of dimensions.
mat = Matrix<int>{9, 2, 8};
mat(5, 1, 7) = 24;
//mat(5, 2) = 17; //throws exception at runtime because of wrong number of dimensions.

这在运行时动态索引中很好用:

And this works fine with runtime-dynamic indexing:

std::vector<size_t> indexes;
/*...*/
mat(indexes) = 54; //Will throw if index count is wrong, will succeed otherwise

此类对象还有许多其他功能可能想像 resize 方法一样,但是选择如何实现它是一个高级设计决策。我还遗漏了大量其他可能有价值的实现细节(例如优化的移动构造函数,比较运算符,复制构造函数),但这应该使您对如何开始有了一个很好的了解。

There are a number of other functions that this kind of object might want, like a resize method, but choosing how to implement that is a high-level design decision. I've also left out tons of other potentially valuable implementation details (like an optimizing move-constructor, a comparison operator, a copy constructor) but this should give you a pretty good idea of how to start.

如果您想完全避免使用模板,则可以将此处提供的代码削减一半,而只需使用使用<$ c的方法/构造函数即可。 $ c> std :: vector< size_t> 提供尺寸/索引数据。如果您不需要在运行时动态适应尺寸数量的功能,则可以删除 std :: vector< size_t> 重载,甚至可以使类本身的模板参数的维数(这将使您可以使用 size_t [] std :: array [size_t,N] 来存储维度数据。

If you want to avoid use of templates entirely, you can cut like half of the code provided here, and just use the methods/constructor that uses std::vector<size_t> to provide dimensions/index data. If you don't need the ability to dynamically adapt at runtime to the number of dimensions, you can remove the std::vector<size_t> overloads, and possibly even make the number of dimensions a template argument for the class itself (which would enable you to use size_t[] or std::array[size_t, N] to store dimensional data).

这篇关于如何制作“杂色”字体?矢量类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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