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
版权声明:本文标题:c++ - Hooking std::plus<T>() to overloaded operator+ - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736301565a1931224.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论