c++ - Using std::transform to Add Vector of Vectors (A) to another Vector of Vectors (B)
问题描述
I'm quite new to using vectors and coding C++ in general and still haven't fully grasped the language yet. My inquiries are as follows:
1. My main problem seems to be my transform line, why is that so?
2. How do I print the vector sums of A and B?
3. How do I overload the [][] operator for access and make it work? (i.e. the code should still work if Mat[1][3] = 4 is written)
#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;
}
I hope you can be patient in helping me fix my code and letting me understand why my syntax is incorrect and uncompilable. Thank you so much <3
解决方案
正如 Jarod42 在评论中指出的那样,您需要添加std::vector<double>
s 的东西,以及添加double
s 的东西。
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;
}
推荐阅读
- anaconda - 使用 Anaconda 更新到 Spyder 4.0.1 时出现问题 - 在 Anaconda Navigator 中更新时恢复到版本 3.3.6
- c# - 将 datetimeoffset(0) 与实体框架数据库一起使用
- c#-4.0 - 比较两个文本文件,但一个由于权限不存在
- python - tkinter:如何从按钮获取结果并在函数中使用它?
- google-oauth - 谷歌是否仍然尊重 https://accounts.google.com/o/oauth2/auth 请求中的“max_age”请求参数?
- php - 获取最新发布的 YouTube 视频 URL
- python - Flask-SQLAlchemy:无法从用户数据库中查询
- docker - 为在 Docker 中运行的 ASP.Net Core 3.1 项目提供开发证书?
- java - 如何在 h2 数据库 Play Framework 2.7.3 中搜索?
- r - 自动从上面的值中减去值 - 没有循环