【发布时间】:2019-12-19 20:47:24
【问题描述】:
正如你在下面的代码中看到的,我想通过 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();
}
提前感谢您的帮助!
附:如果有人还可以告诉我如何更好地将向量传递给函数以及如何将模板“typename”用于 main 将不胜感激。
【问题讨论】:
-
"如何使用模板 "typename" 作为 main" - 现在忘记这个。
main很特别,您可以不将其设为模板。 -
而不是尝试用
A(r, std::vector<T>(c));“初始化”你应该只调整向量的大小(因为它已经存在),例如:A.resize(r, std::vector<T>(c)); -
@UnholySheep 你先生是个该死的天才! ty :D