簡體   English   中英

使用 std::transform 將向量的向量 (A) 添加到另一個向量的向量 (B)

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM