使用 std::transform 将向量向量 (a) 添加到另一个向量向量 (b)

Using std::transform to Add Vector of Vectors (A) to another Vector of Vectors (B)

本文关键字:向量 另一个 添加 使用 transform std      更新时间:2023-10-16

我对使用向量和编码C++很陌生,但还没有完全掌握这门语言。我的询问如下:

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>s 的东西,以及添加doubles 的东西。

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;
}

现场观看!