سؤال

I'm calculating the determinant of a matrix, the calculations and therefore a method is called depending on the dimensionality of the data, for example:

template<int X, int Y>
float determinant(X, Y, std::vector<Vector> &data)
{
    // Determine the dimensionality of matrix data (x and y) 
}

The problem that I am having is that in the class that calculates the PCA, which calls this function, only accepts an iterator:

class PCA { 

   public: 

      template<typename T> 
      PCA(T begin, T end)
      {
          // Determine the X and Y here
          float det = determinant(X, Y, ....); 
      }
}; 

Now I am wondering whether or not it is possible to deduce the X and Y from the iterator that has been passed through PCA, rather than passing in two integer values.

Any advice would be greatly appreciated

EDIT:

Apologises, my question was not clear.

Basically, typedef std::vector<double> Vector; is used so therefore std::vector<Vector> data; would therefore be a vector of vectors.

I sample this doing the following:

std::vector<Vector> data1 = { {1, 2}, {3, 4}, {5, 6}, {8, 9} }; // 2x2 whereas when I want to add the following: std::vector<Vector> data2 = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12} }; // 3x3 so obviously, when calculating the determinant there is a different calculation for this.

I want to deduce that data1 is a 2x2 and data2 3x3 from the function without having to specifically pass these values in.

هل كانت مفيدة؟

المحلول

Since vectors aren't fixed-size, they could be jagged. (Constrast this with, e.g. std::array<> or T [N][M][L]; you could deduce their ranks at compiletime).

Let's assume they're not: see it Live On Coliru

#include <vector>
#include <cstdint>
#include <deque>

template <typename V>
    std::deque<std::size_t> dims_of(V const& v) {
    return {};
}

template <typename T>
    std::deque<std::size_t> dims_of(std::vector<T> const& v)
{
    if (v.empty())
        return { 0 };
    else
    {
        auto dims = dims_of(v.front());
        dims.push_front(v.size());
        return dims;
    }
}

#include <iostream>

int main()
{
    std::vector<std::vector<std::vector<int> > > const
        v(7, std::vector<std::vector<int> >(
            10, std::vector<int>(3, 0)
            )
         );

    for (auto dim : dims_of(v))
        std::cout << dim << " ";

} 

Prints

7 10 3 

نصائح أخرى

What about deriving from PCA into class that holds X and Y

template<int X,int Y>
PCA_size : public PCA
{
      enum { Xv=X};
      enum { Yv=Y};

}

Then you can just recast existing PCA object into yours

 static_cast<PCA_size<3,5> >(PCA_instance);
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top