2014-02-07 62 views
0

有什么方法可以计算动态分配数组中的元素数量吗?使用静态分配的数组它没有用(它给了我堆栈溢出错误),因为我需要分配一个缓冲区大小来存储100,000个双精度值(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)即ie我们为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; 
+0

什么不好吗了解矢量?听起来像矢量是你的问题的确切答案... – John3136

+0

_''m_vector.data()'函数只适用于**文本数据**,是吗?'_呃,什么? –

+3

std :: vector有一个函数size(),它会给你的矢量大小。 – sunny1304

回答

4

而不是使用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(); 
+0

您能否提一下可用于保存所有元素数据的内容。就像我们用char类型的vector一样,并使用data()来保存数据元素。 – User

+1

@ user3232405'std :: vector <> :: data()'不意味着用于您想要执行的操作。使用'resize()'和'size()'来分配/确定你想要的'double'项目的数量。 –

1

如果你真的想双打的阵列的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'; 
}