以下代码的内存要求如何与代码长度无关? < >上面的C++代码要求内存范围从2.9……MB或更大,到3.04……MB或更大。 并考虑下面的C代码: // An efficient program to randomly select a number from stream of numbers. #include <iostream> using namespace std; #include <stdlib.h> #include <time.h> /* A program to randomly select a item from stream[0], stream[1], .. stream[i-1]*/ int main() { int stream[] = { 1, 2, 3, 4 }; int n = sizeof(stream) / sizeof(stream[0]); // Use a different seed value for every run. srand(time(0)); cout << "Random no. selected: " << stream[(rand() % n)] << "\n"; return 0; }
上面的代码需要1.28 MB或更大的内存,但肯定小于2MB以下代码的内存要求如何与代码长度无关? < >上面的C++代码要求内存范围从2.9……MB或更大,到3.04……MB或更大。 并考虑下面的C代码: // An efficient program to randomly select a number from stream of numbers. #include <iostream> using namespace std; #include <stdlib.h> #include <time.h> /* A program to randomly select a item from stream[0], stream[1], .. stream[i-1]*/ int main() { int stream[] = { 1, 2, 3, 4 }; int n = sizeof(stream) / sizeof(stream[0]); // Use a different seed value for every run. srand(time(0)); cout << "Random no. selected: " << stream[(rand() % n)] << "\n"; return 0; },c++,memory,random,space-complexity,srand,C++,Memory,Random,Space Complexity,Srand,上面的代码需要1.28 MB或更大的内存,但肯定小于2MB 我的问题是,为什么第一个程序比第二个程序占用更多的空间,以及如何使用?使用提供的在线编辑器,内存使用似乎与实际分配不符。如果我用内存stat写一个程序,这和我做的是一样的。我相信这个数据只是可执行文件的大小。当你说内存时,你是说进程需要的内存还是它在磁盘上的大小?@NathanOliver,你的操作系统、编译器、优化设置是什么?@NathanOliver我不确定,但这应该与程序的空间复杂度有关。@SergeyA,你是想打电话给我吗?我想
我的问题是,为什么第一个程序比第二个程序占用更多的空间,以及如何使用?使用提供的在线编辑器,内存使用似乎与实际分配不符。如果我用内存stat写一个程序,这和我做的是一样的。我相信这个数据只是可执行文件的大小。当你说内存时,你是说进程需要的内存还是它在磁盘上的大小?@NathanOliver,你的操作系统、编译器、优化设置是什么?@NathanOliver我不确定,但这应该与程序的空间复杂度有关。@SergeyA,你是想打电话给我吗?我想对于第二个例子中的初学者来说,你运行的循环每次都需要更多的内存。谢谢你的回答,是的,我检查了同样的问题,但发现使用malloc有时会显示出比,当它没用的时候…不明白为什么?
/* An efficient program to randomly select a number from
stream of numbers.*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
/* A function to randomly select a item from stream[0], stream[1], ..
stream[i - 1]*/
int selectRandom(int x)
{
static int res; // The resultant random number
static int count = 0; //Count of numbers visited so far in stream
count++; // increment count of numbers seen so far
// If this is the first element from stream, return it
if (count == 1)
res = x;
else
{
// Generate a random number from 0 to count - 1
int i = rand() % count;
// Replace the prev random number with new number with 1/count
//probability
if (i == count - 1)
res = x;
}
return res;
}
// Driver program to test above function.
int main()
{
int stream[] = { 1, 2, 3, 4 };
int n = sizeof(stream) / sizeof(stream[0]);
// Use a different seed value for every run.
srand(time(NULL));
for (int i = 0; i < n; ++i)
printf("Random number from first %d numbers is %d \n",
i + 1, selectRandom(stream[i]));
return 0;
}