|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
#include <iostream>
using namespace std;
template <class T>
T sum(T *a,int length) {
T sum = 0;
for (int i = 0; i < length; i++) {
sum += a[i];
}
return sum;
}
int GetArrayLength(const T(&)[N])
{
return N;
}
void main() {
int a[] = { 1,2,3,4,5,6,7,8,9,10 };
int length = GetArrayLength(a);
int sum_int = sum(a,length);
printf("总长度为:%d\nsum= %d\n",length , sum_int);
system("PAUSE");
}
#include <iostream>
using namespace std;
template<class T>
void display(T& a,int n){
cout<<"该数组为:"<<endl;
for(int i=0;i<n;i++)
cout<<a[i]<<"\t";
cout<<endl;
}
template <class T>
T sum(T a[], size_t n)
{
T sum = 0;
for (size_t i = 0; i < n; i++)
{
sum += a[i];
}
return sum;
}
void main()
{
int a[] = {1,2,3,4,5,6,7,8,9};
display(a,9);
cout<<"该数组元素之和为:"<<sum(a, 9)<<endl;
}
上面是我编写的一个求数组元素和的一个程序,可以有大佬在其中利用函数模板编写一个求数组长度的程序吗?
我之前编写的用VC 6.0运行不出来,不知道应该怎么办?希望得到大佬们的帮助。
#include <iostream>
template <typename T, size_t N>
/*适用一维数组*/
size_t GetArrayLength(const T (&arr)[N])
{
return N;
}
template <typename T, size_t N>
/*二维数组*/
size_t GetArrayLength(const T *(&arr)[N])
{
return N;
}
int main(int argc, char const *argv[])
{
int arr[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
std::cout << "arr[] --- " << GetArrayLength(arr) << std::endl;
char ch[] = "hello";
std::cout << "ch[] --- " << GetArrayLength(ch) << std::endl;
double arr1[][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
std::cout << "arr1[][] --- " << GetArrayLength(arr1) << std::endl;
char ch1[][6] = {"hello", "fishC", "Clang", "&C++"};
std::cout << "ch1[][] --- " << GetArrayLength(ch1) << std::endl;
return 0;
}
-------------------------------------------------------------------------------
Microsoft Windows [版本 10.0.18363.418]
(c) 2019 Microsoft Corporation。保留所有权利。
E:\Users\admin\Documents\VScode>c:\Users\admin\.vscode\extensions\ms-vscode.cpptools-0.26.1\debugAdapters\bin\WindowsDebugLauncher.exe --stdin=Microsoft-MIEngine-In-sbztw5o1.xqm --stdout=Microsoft-MIEngine-Out-jisfivrp.1vv --stderr=Microsoft-MIEngine-Error-m1ykmf1z.1ho --pid=Microsoft-MIEngine-Pid-uxwp34jl.bmh --dbgExe=D:\MinGW\bin\gdb.exe --interpreter=mi
arr[] --- 11
ch[] --- 6
arr1[][] --- 3
ch1[][] --- 4
E:\Users\admin\Documents\VScode>
|
|