动态和静态分配数组元素计算

Dynamically and Statically allocated Array elements calculation?

本文关键字:数组元素 计算 分配 静态 动态      更新时间:2023-10-16

有什么方法可以计算动态分配数组中的元素数量吗?使用静态分配的数组是无效的(这会导致堆栈溢出错误),因为我需要分配一个缓冲区大小来存储100000个双值(100000*8=800000字节)的数据。不管怎么说,我没能用静态数组做到这一点,但我真的不想在堆栈上分配这么大的缓冲区,相反,堆将是首选。

这就是我所做的。

静态分配的数组,这里的大小是我实际需要的(在这种情况下肯定会失败),但我尝试了一些较小的大小,它为我打印了but this is not what i want i need something which can count how many elements are actually entered by for loop not just return whole size (800010*8)的元素数量,即类似于我们为char buffer[1000]strlen(buffer)所做的事情。

srand (time(0));
double arr[800010];
for(int i = 0; i < 100000; i++)
{    
arr[i] = (rand()%10000)+(134.234*i); 
std::cout<<"is"<<arr[i]<<std::endl;
}
int numelements = sizeof(arr)/sizeof(arr[0]);
std::cout<<"num elements are"<<numelements*8;//multiplied by 8 is size of double;

动态分配是好的,堆上的内存分配没有问题,但"num elements are" = 0?如果有人建议使用std::vector<double>m_vector,请建议我如何将其作为数组传递,因为m_vector.data()函数仅适用于文本数据,是吗?或者,如果有什么想法的话,我该如何计算元素的实际数量?请不要说做100000*8。我正在寻找一些合乎逻辑的方法来做到这一点。

srand (time(0));
double *arr = new double[800010];
for(int i = 0; i < 100000; i++)
{    
arr[i] = (rand()%10000)+(134.234*i); 
std::cout<<"is"<<arr[i]<<std::endl;
}
int numelements = sizeof(arr)/sizeof(arr[0]);
std::cout<<"num elements are"<<numelements*8;

不要使用new[]来分配数组,而是使用std::vector。它将为您跟踪大小,并负责释放底层内存。

例如:

std::vector<double> arr(100000);
for(int i = 0; i < arr.size(); i++)
{    
arr[i] = (rand()%10000) + (134.234*i); 
std::cout << "is" <<arr [i] << std::endl;
}
int numelements = arr.size();

如果你真的想要一个双精度数组的c字符串表示,你可以存储一个NaN作为终止元素:

#include <iostream>
#include <limits>
#include <sstream>
#include <vector>
std::size_t nan_terminated_length(const double* d) {
std::size_t result = 0;
while(d[result] == d[result]) ++result; // C++11: std::isnan
return result;
}
int main() {
std::istringstream input("1.0 2.0 3.0");
std::vector<double> buffer;
buffer.reserve(1024);
double d;
while(input >> d) {
buffer.push_back(d);
}
buffer.push_back(std::numeric_limits<double>::quiet_NaN());
std::cout
<< "Number of elements: "
<< nan_terminated_length(buffer.data())
<< " which is (in this case) equal to the"
" size of the vector minus one: "
<< buffer.size() - 1
<< 'n';
}