c++中,为什么头文件包含了stdlib.h,但是random函数显示有错

c++中,为什么头文件包含了stdlib.h,但是random函数显示有错。

2012年04月12日 16:07:08 oneboyishappy 阅读数:10782

 
  1. #include <iostream>

  2. #include <stdlib.h> // Need random(), srandom()

  3. #include <time.h> // Need time()

  4. #include <algorithm> // Need sort(), copy()

  5. #include <vector> // Need vector

  6.  
  7. using namespace std;

  8.  
  9. void Display(vector<int>& v, const char* s);

  10.  
  11. int main()

  12. {

  13. // Seed the random number generator

  14. srandom( time(NULL) );

  15.  
  16. // Construct vector and fill with random integer values

  17. vector<int> collection(10);

  18. for (int i = 0; i < 10; i++)

  19. collection[i] = random() % 10000;

  20.  
  21. // Display, sort, and redisplay

  22. Display(collection, "Before sorting");

  23. sort(collection.begin(), collection.end());

  24. Display(collection, "After sorting");

  25. return 0;

  26. }

  27.  
  28. // Display labels and contents of integer vector v

  29. void Display(vector<int>& v, const char* s)

  30. {

  31. cout << endl << s << endl;

  32. copy(v.begin(), v.end(),ostream_iterator<int>(cout, "\t"));

  33. cout << endl;

  34. }


运行:

3.cpp
E:\workspace\test\3.cpp(14) : error C2065: 'srandom' : undeclared identifier
E:\workspace\test\3.cpp(19) : error C2065: 'random' : undeclared identifier
执行 cl.exe 时出错.

2.exe - 1 error(s), 0 warning(s)

原来:在linux下stdlib.h包含srandom 和random ,但在VC下stdlib.h包含的是srand和rand,所以应该改过来

 
  1. #include <iostream>

  2. #include <stdlib.h> // Need random(), srandom()

  3. #include <time.h> // Need time()

  4. #include <algorithm> // Need sort(), copy()

  5. #include <vector> // Need vector

  6.  
  7. using namespace std;

  8.  
  9. void Display(vector<int>& v, const char* s);

  10.  
  11. int main()

  12. {

  13. // Seed the random number generator

  14. srand( time(NULL) ); // srandom----->srand

  15.  
  16. // Construct vector and fill with random integer values

  17. vector<int> collection(10);

  18. for (int i = 0; i < 10; i++)

  19. collection[i] = rand() % 10000; // random----->rand

  20.  
  21. // Display, sort, and redisplay

  22. Display(collection, "Before sorting");

  23. sort(collection.begin(), collection.end());

  24. Display(collection, "After sorting");

  25. return 0;

  26. }

  27.  
  28. // Display labels and contents of integer vector v

  29. void Display(vector<int>& v, const char* s)

  30. {

  31. cout << endl << s << endl;

  32. copy(v.begin(), v.end(),ostream_iterator<int>(cout, "\t"));

  33. cout << endl;

  34. }

  35.  

猜你喜欢

转载自blog.csdn.net/boshuzhang/article/details/88741425