简体   繁体   中英

C++ Passing through a function an std::array of std::array

I'm new with std::array. I have to create this function

void foo(std::array < std::array <double, a>& , b> & previous)

where a and b are two fixed integer values. How should I do?

Thank you in advance!

The "variables" a and b must be compile-time constants. If you want them to be variable or set during runtime, you must use std::vector instead.

Template arguments (such as those to std::array ) must be known at compile time. To be general, you can write a function that is templated on the two sizes, eg:

template <std::size_t N, std::size_t M>
void foo(std::array<std::array<double, N>, M> &previous) {
    // code goes here, e.g.:
    previous[M - 1][N - 1] = static_cast<double>(M * N);
}

The template arguments will be deduced by the function argument type, so your array of arrays can have any dimensions you want and you don't need to specify them when calling foo .

std::array<std::array<double, 10>, 20> my_array;
foo(my_array); // equivalent to foo<10, 20>(my_array);

By the way, using std::vector<std::vector<T>> is a terrible, awful idea if you want your program to be robust or fast. Not only must you manually manange and carefully track each inner vector 's length, you also take a huge performance hit by individually heap-allocating N M -length arrays rather than, say, a single N x M -length array.

As mentioned pmttavara you can perform compile time deduction of the dimensions and type.

template <typename Scalar, std::size_t I, std::size_t J>
void
Foo(std::array<std::array<Scalar, I>, J>& previous) {
}

int main() {
        std::array<std::array<double, 10>, 20> data;
        Foo(data);
}

Alternatively you can treat this data like a matrix.

template <typename Scalar>
class Matrix {
public:
    Matrix(std::size_t rows, std::size_t cols)
        : rows(rows)
        , cols(cols)
        , data(rows * cols, Scalar(0))
    {}

    Scalar&
    at(std::size_t row, std::size_t col) {
        std::size_t n = (row * cols) + col;
        return data.at(n);
    }

private:
    std::size_t rows;
    std::size_t cols;
    std::vector<Scalar> data;
};

int main() {
        Matrix<double> m(3, 3);
        m.at(2, 2) = 3;
}

a and b must be known at compil time. You can declare them as

constexpr int a = 10;
constexpr int b = 100;

If is not possible to know at compile-time this two variable you have to use std::vectors instead:

typedef std::vector< const std::vector > Matrix;
void f( const Matrix& m );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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