动态和静态分配数组元素计算
Dynamically and Statically allocated Array elements calculation?
有什么方法可以计算动态分配数组中的元素数量吗?使用静态分配的数组是无效的(这会导致堆栈溢出错误),因为我需要分配一个缓冲区大小来存储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';
}
相关文章:
- 数组元素打印的递归方法
- C++数据文件、数组和计算赋值
- 如何将字节数组元素替换为修改的十六进制 ASCII 符号?
- 为什么使用数组元素查找最大数字的程序不起作用?
- 数组元素更改值?
- 如何访问宏中定义的数组元素
- 将数组元素递增 1
- C++函数,它将数组、谓词和运算符作为参数,并将运算符应用于满足谓词的数组元素
- 存储指向动态数组元素的指针
- C++通过别名指针以静默方式将错误的类型分配给数组元素
- 如何在 c++ 中计算相同数组元素的数量
- 我写了这个简单的代码,应该计算一系列数组元素的最高数量,但结果很奇怪
- 避免在函数调用中计算数组元素
- 为什么数组元素长度的地址计算可被 2 的幂整除更有效
- OpenCV函数来计算类似于MATLAB产品的数组元素的乘积?
- 计算字符串/数组元素的十六进制,然后将其转换为十进制
- 计算数组元素的平均值并显示它们
- 优化了数组元素的计算和设置
- 使用数组元素执行计算
- 计算数组元素中不同绝对值的个数