繁体   English   中英

C++ 通过函数声明后初始化向量

[英]C++ Initialising vector after declaration through a function

正如您在以下代码中看到的,我想通过 Allocate 函数分配 main 中声明的向量的大小和元素。

错误消息

.\MV_Produkt.cpp: In instantiation of 'void Allocation(std::vector<std::vector<T> >&, std::vector<T>&) [with T = double]':

.\MV_Produkt.cpp:44:20:   required from here

.\MV_Produkt.cpp:11:6: error: no match for call to '(std::vector<std::vector<double> >) (int&, std::vector<double>)' -----A(r, std::vector<T>(c));

.\MV_Produkt.cpp:19:6: error: no match for call to '(std::vector<double>) (int&)'-----x(c);
#include<iostream>
#include<fstream>
#include<vector>
#include<algorithm>

template<typename T>
void Allocation(std::vector<std::vector<T>>& A,std::vector<T>& x){
    std::ifstream inA("A.txt");
    int r, c;
    inA >> r >> c;
    A(r, std::vector<T>(c));
    for(size_t i=0;i<A.size();i++)
        for(size_t j=0;j<A[i].size();j++)
            inA >> A.at(i).at(j);
    inA.close();

    std::ifstream inx("x.txt");
    inx >> c;
    x(c);
    typename std::vector<T>::iterator xi;
    for(xi=x.begin();xi!=x.end();xi++)
        inx >> *xi;
    inx.close();
}

template<typename T>
void MV_Product(const std::vector<std::vector<T>> A,const std::vector<T> x, std::vector<T>& b){
    typename std::vector<std::vector<T>>::const_iterator row;
    typename std::vector<T>::const_iterator colA;
    typename std::vector<T>::const_iterator colx;
    typename std::vector<T>::iterator colb;

    for(row=A.cbegin();row<A.cend();row++)
        for(colA=row->cbegin(),colx=x.cbegin(),colb=b.begin();colA<row->cend(),colx<x.cend(),colb<b.end();colA++,colx++,colb++)
            *colb = *colA * *colx;
}

int main(){
    std::vector<std::vector<double>> A;
    std::vector<double> x;
    std::vector<double> b;
    std::vector<double>::iterator bi;

    Allocation(A, x);
    MV_Product(A,x,b);

    std::ofstream outb("b.txt");
    outb << b.size() << " " << *min(b.begin(),b.end()) << " " << *max(b.begin(),b.end()) << std::endl;
    for(bi=b.begin();bi<b.end();bi++)
        outb << *bi << std::endl;
    outb.close();
}

提前感谢您的任何帮助!

PS 如果有人也能告诉我如何更好地将向量传递给函数以及如何使用模板“typename”作为 main 将不胜感激。

“如何更好地将向量传递给函数?”

  • 它通常通过引用传递向量,因此函数可以反映向量的变化。 例如: void foo(vector<int> &bar);

  • 您还可以传递向量的副本,也许您想使用/操作此向量的内容,但任何更改都不会反映在传递的向量上,您只需使用“副本”即可。 例如: void foo(vector<int> bar);

  • 传递const引用,当您不希望函数更改向量的内容时,这既有效又可靠。 例如: void foo(vector<int> const &bar);
  • 当然你可以传递一个指向向量的指针,但是除非你知道你在做什么并且你觉得这确实是要走的路,否则不要这样做。 例如: void foo(vector<int> *bar);

  • 请在Geeks4Geeks上检查这个问题和“将向量传递给函数

在您的代码中,您可以在此处的错误消息中看到

\\MV_Produkt.cpp:11:6: error: no match for call to '(std::vector<std::vector<double> >) (int&, std::vector<double>)' -----A(r, std::vector<T>(c));

\\MV_Produkt.cpp:19:6: error: no match for call to '(std::vector<double>) (int&)'-----x(c);

您在主函数中用于 T double ,而在Allocation函数中将其用作int ,因此您定义的内容与传递的内容不匹配。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM