#include <iostream>
template <typename T>
void Len(T a[200])
{
std::cout<< sizeof(a) / sizeof(a[0])<<std::endl;
}
int main()
{
int a[300];
std::cout<<"Put the values of array you want."<<std::endl;
std::cin>>a;
std::cout<<"The number of occurrences of value in the array is";
Len(a);
}
为什么这段代码在 std::cin>>a 中出错? 我几乎是第一次用 C++ 编写代码。 请回答:(
最佳答案
你不能像std::cin >> a;
那样直接输入数组。您需要做的是遍历数组并将输入插入到每个元素中。你可以这样做
for(int i = 0; i < array_size && std::cin >> array_name[i]; ++i) {}
您的数组大小函数也不正确。
template <typename T>
void Len(T a[200])
{
std::cout<< sizeof(a) / sizeof(a[0])<<std::endl;
}
这里 a
将衰减为一个指针,返回的大小将是 sizeof(T*)/sizeof(T)
如果你想得到你可以使用的数组的大小
template <typename T, typename size_t N>
size_t get_array_size(T (&)[N])
{
return N;
}
关于c++ - 不匹配运算符,为什么这段代码没有得到 cin?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32843910/