admin管理员组

文章数量:1122832

I practice easy coding on Codewars platform. There is a place where I found following exercise:

Write a function that accepts two square matrices (N x N two dimensional arrays), and return the sum of the two. Both matrices being passed into the function will be of size N x N (square), containing only integers.

My first iteration of solution used definition of overloaded operator+ for vectors. I thought of them as 1-dimensional matrices. Code was following:

template <typename T>
std::vector<T> operator+(const std::vector<T>& a, const std::vector<T>& b) {
    assert (a.size() == b.size());

    std::vector<T> sum;
    sum.reserve(a.size());

    std::transform(
        a.begin(),
        a.end(),
        b.begin(),
        std::back_inserter(sum),
        std::plus<T>()
    );
    return sum;
}

When I used this overloaded operator in for-loop going through 2-nd dimension of the matrices, basically exercise was solved. But I wanted to go one step further and write overloaded operator+ for 2-dimensional vectors. So I wanted in the end solution working like that:

std::vector<std::vector<int> > matrixAddition(std::vector<std::vector<int> > a,std::vector<std::vector<int> > b){
    std::vector<std::vector<int>> sum;
    sum = a + b;
    return sum;
}

However, implementation of operator+ for 2-dim vectors doesn't compile. This is the code:

template <typename T>
std::vector<std::vector<T>> operator+(const std::vector<std::vector<T>>& a, const std::vector<std::vector<T>>& b) {
    /*
     * Add 2-dimensional vectors
     * */
    assert (a.size() == b.size());

    std::vector<std::vector<T>> sum;

    // Allocate memory for 2nd dimension
    size_t dim2size = a.size();
    sum.reserve(dim2size);

    // Allocate memory for 1st dimension
    size_t dim1size = a[0].size();
    for (size_t i=0; i<dim2size; i++)
        sum[i].reserve(dim1size);

    std::transform(
            a.begin(),
            a.end(),
            b.begin(),
            std::back_inserter(sum),
            std::plus<std::vector<T>>()
    );
    return sum;
}

I'm getting a compilation error:

/usr/include/c++/14/bits/stl_function.h:190:20: error: no match for ‘operator+’ (operand types are ‘const std::vector’ and ‘const std::vector’)

Btw my friend told me I can use a lambda function instead of std::plus<std::vector<T>>():

[](const std::vector<int>&a, const std::vector<int>& b)  {return a+b;}

But do you know what I'm doing from when calling std::plus<std::vector<T>>()?

本文标签: cHooking stdplusltTgt() to overloaded operatorStack Overflow