gpt4 book ai didi

c++ - 如何编写一个模板函数,它接受一个数组和一个指定数组大小的 int

转载 作者:太空狗 更新时间:2023-10-29 23:25:23 26 4
gpt4 key购买 nike

在一次大学练习中,我被要求编写一个模板函数“print();”,它有两个参数,1:泛型数组,2:指定数组大小的 int。然后该函数应将数组中的每个项目打印到控制台。我在函数参数方面遇到了一些麻烦。我目前的代码是:

   template <typename Type>
Type print (Type a, Type b)
{
Type items;
Type array;
a = array;
b = items;

for (int i = 0; i < items; i++) {
std::cout << std::endl << "The element of the index " << i << " is " << array << std::endl;
std::cout << std::endl;
}

在 main() 中:

    print(Array[], 10);

显然将 Array 作为参数并没有返回值,所以我不确定还能做什么。有什么想法吗?

最佳答案

正确的写法是

Live On Coliru

#include <iostream>

template <typename T, size_t size> void print(const T (&array)[size])
{
for(size_t i = 0; i < size; ++i)
std::cout << array[i] << " ";
}

int main() {
int arr[] = { 1,2,3,4,99};

print(arr);
}

打印

1 2 3 4 99

关于c++ - 如何编写一个模板函数,它接受一个数组和一个指定数组大小的 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33234979/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com