[英]Using std::transform to Add Vector of Vectors (A) to another Vector of Vectors (B)
我对使用向量和编码 C++ 还很陌生,但还没有完全掌握这门语言。 我的查询如下:
line, why is that so? 1.我的主要问题似乎是我的线,为什么会这样?
2. 如何打印 A 和 B 的向量和?
3. 如何重载 [][] 运算符以进行访问并使其工作? (即,如果写入 Mat[1][3] = 4,代码仍然可以工作)
#include <iostream>
#include <algorithm>
#include <vector>
#include <functional>
using namespace std;
class Matrix
{
public:
double x;
vector<vector<double> > I{ { 1, 0, 0, 0 },
{ 0, 1, 0, 0 },
{ 0, 0, 1, 0 },
{ 0, 0, 0, 1 } };
vector<vector<double> > Initialization(vector<vector<double> > I, double x);
vector<vector<double> > Copy(vector<vector<double> > I);
void Print(vector<vector<double> > I);
};
vector<vector<double> > Matrix::Initialization(vector<vector<double> > I, double x)
{
for (int i = 0; i < I.size(); i++) {
for (int j = 0; j < I[i].size(); j++)
{
// new matrix
I[i][j] *= x;
}
}
return I;
};
vector<vector<double> > Matrix::Copy(vector<vector<double> > I)
{
vector<vector<double> > I_copy = I;
return I_copy;
};
void Matrix::Print(vector<vector<double> > I)
{
for (int i = 0; i < I.size(); i++) {
for (int j = 0; j < I[i].size(); j++)
{
cout << I[i][j] << " ";
}
cout << endl;
}
};
int main()
{
Matrix m;
vector<vector<double> > A;
vector<vector<double> > B;
cin >> m.x;
A = m.Initialization(m.I, m.x);
B = m.Copy(A);
m.Print(A);
m.Print(B);
B.resize(A.size());
transform(A.begin(), A.end(), B.begin(), A.begin(), plus<double>());
return 0;
}
我希望您能耐心帮助我修复我的代码,并让我理解为什么我的语法不正确且无法编译。 非常感谢<3
正如 Jarod42 在评论中指出的那样,您需要添加std::vector<double>
的东西,以及添加double
的东西。
template <typename T>
std::vector<T> operator+(std::vector<T> lhs, const std::vector<T> & rhs)
{
std::transform(lhs.begin(), lhs.end(), rhs.begin(), lhs.begin(), [](const T & a, const T & b){ return a + b; });
return lhs;
}
请注意,我们复制了左侧,但仅引用了右侧。 这也为我们提供了将结果写入的地方。
用法很简单
int main()
{
std::vector<std::vector<double> > A { { 0, 1 }, { 1, 0 } };
std::vector<std::vector<double> > B { { 1, 0 }, { 0, 1 } };
std::vector<std::vector<double> > C { { 1, 1 }, { 1, 1 } };
std::cout << std::boolalpha << (A + B == C) << std::endl;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.