注册 登录
编程论坛 C++教室

[求助]编译出错,帮一下.

nuciewth 发布于 2006-12-16 22:12, 409 次点击
#include<iostream.h>
template<class Type,int Rows,int Cols>
void sumAll(Type data[][Cols],Type result[])
{
for(int i=0;i<Rows;i++)
{
result[i]=0;
for(int j=0;j<Cols;j++)
result[i]+=data[i][j];
}
}
void main()
{
int d[][3]={{1,2,3},{2,3,4},{2,5,3},{3,5,9},{8,9,4}};
int r[5];
sumAll<int,5,3>(d,r);//必需强制实例转化
cout<<r[0]<<' '<<r[1]<<' '<<r[2]<<' '<<r[3]<<' '<<r[4]<<endl;
double dd[][4]={{1.2,1.3,5.2,3.3},{2.2,1.4,0.4,4.2},{7.2,2.3,8.2,5.8},{2.4,3.5,5.4,6.3}};
double rr[4];
sumAll<double,4,4>(dd,rr);//必需强制实例转化
cout<<rr[0]<<' '<<rr[1]<<' '<<rr[2]<<' '<<rr[3]<<endl;
}

error C2087: '<Unknown>' : missing subscript
5 回复
#2
wangxiang2006-12-16 23:16
不能那么用啊
你要那么用的话,得动态分配内存
#3
zzymoon2006-12-16 23:20
太高深了```
我没有接触到template```
帮不了``
#4
wangxiang2006-12-16 23:55

#include <iostream>
#include <vector>
using namespace std;
template<class type>
void sumAll(vector< vector<type> > vvec,vector<type> &vec)
{
for(size_t i = 0; i < vvec.size(); i++)
{
type result = 0;
for(size_t j = 0; j < vvec[i].size(); j++)
result += vvec[i][j];
vec.push_back(result);
}
}
int main()
{
vector< vector<int> > ivvec;
vector<int> ivec1,ivec2,ivec3;
ivec1.push_back(1);
ivec1.push_back(2);
ivec1.push_back(3);
ivec2.push_back(2);
ivec2.push_back(3);
ivec2.push_back(4);
ivvec.push_back(ivec1);
ivvec.push_back(ivec2);
sumAll(ivvec,ivec3);
for(size_t size = 0; size < ivec3.size(); size++)
cout<<ivec3[size]<<" ";
cout<<endl;
system("pause");
return 0;
}

#5
nuciewth2006-12-17 18:28
以下是引用wangxiang在2006-12-16 23:16:12的发言:
不能那么用啊
你要那么用的话,得动态分配内存

能说一下原因吗?谢谢.

#6
wangxiang2006-12-17 22:46
不好意思,我错了,是可以那么用的
看来你用的是VC6.0换个DEV—CPP吧
你的程序没错
#include<iostream>
using namespace std;
template<class Type,int Rows,int Cols>
void sumAll(Type data[][Cols],Type result[])
{
for(int i=0;i<Rows;i++)
{
result[i]=0;
for(int j=0;j<Cols;j++)
result[i]+=data[i][j];
}
}
int main()
{
int d[][3]={{1,2,3},{2,3,4},{2,5,3},{3,5,9},{8,9,4}};
int r[5];
sumAll<int,5,3>(d,r);//必需强制实例转化
cout<<r[0]<<' '<<r[1]<<' '<<r[2]<<' '<<r[3]<<' '<<r[4]<<endl;
double dd[][4]={{1.2,1.3,5.2,3.3},{2.2,1.4,0.4,4.2},{7.2,2.3,8.2,5.8},{2.4,3.5,5.4,6.3}};
double rr[4];
sumAll<double,4,4>(dd,rr);//必需强制实例转化
cout<<rr[0]<<' '<<rr[1]<<' '<<rr[2]<<' '<<rr[3]<<endl;
system("pause");
return 0;
}
1