提问人:semicolon_missing 提问时间:8/19/2023 最后编辑:Remy Lebeausemicolon_missing 更新时间:8/20/2023 访问量:82
如何在 C++ 中使用 sizeof() 进行reference_to_array [duplicate]
how to use sizeof() for reference_to_array in c++ [duplicate]
问:
如何使用来确定对数组的引用的大小?sizeof()
我已经声明了一个数组,并用于打印它所占用的总大小。main()
sizeof()
然后,我将数组作为对数组的引用传递给函数,但我无法用于引用(数组)变量。sizeof()
#include <iostream>
double sum(double (&list)[], size_t size);
int main(){
double arr[]{34.5, 67.8, 92.345, 8.1234, 12.314, 3.4};
double result{};
std::cout << "size of the array : " << sizeof(arr) << std::endl;
result = sum(arr, std::size(arr));
std::cout << "the total is " << result << std::endl;
return 0;
}
double sum(double (&list)[], size_t size){
double total{};
std::cout << "the size is : " << sizeof(list) << std::endl;
for( int i{} ; i < size ; i++){
total += list[i];
}
return total;
}
sizeof(list)
显示编译器错误:
error: invalid application of ‘sizeof’ to incomplete type ‘double []’
std::cout << "the size is : " << sizeof(list) << std::endl;
在我得到我想要的输出时更改函数参数后,但是为什么没有像声明时那样工作,而没有在声明中明确提及其大小,尽管它是一个参考?double (&list)[6]
sizeof(list)
sizeof(arr)
list
答:
2赞
machine_1
8/19/2023
#1
C 样式数组的大小是其类型的一部分,因此声明为的数组具有完整类型。double arr[6];
(double)[6].
运算符在编译时工作。在数组上使用时,它会返回数组的大小(以字节为单位)。这是可能的,因为数组的大小是其类型的一部分,并且编译器在编译时就知道它。sizeof
sizeof
但是,如果您尝试在不完整的类型(如 )上使用,这将导致编译错误,因为参数的类型必须是完整的。sizeof
(double)[]
sizeof
1赞
Pepijn Kramer
8/20/2023
#2
使用 C++ 我希望这样的代码没有任何大小:
#include <iostream>
#include <numeric>
#include <vector>
double sum(const std::vector<double>& values)
{
double sum{ 0.0 };
// IF you want to write loops, prefer using range based for loops (they will 'know' the size of values)
for (const auto value : values)
{
sum += value;
}
return sum;
}
int main()
{
std::vector<double> values{ 34.5, 67.8, 92.345, 8.1234, 12.314, 3.4 };
double result = sum(values);
// no need to use sizeof in current C++, just ask the vector
std::cout << "size of the array : " << values.size() << "\n";
std::cout << "the total is " << result << "\n";
// or to write code with no loops (in your code) at all
std::cout << "the total using accumulate is " << std::accumulate(values.begin(), values.end(), 0.0);
return 0;
}
评论
sizeof
std::array
std::vector
std::array
std::vector
std::span
sizeof
main
std::size(arr), and compare it with
template <size_t N> double sum(double (&list)[N]);
double sum(double *list, size_t size);