首页 > 解决方案 > 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

标签: c++vectorsumoverloadingaddition

解决方案


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

现场观看!


推荐阅读