在 C++ 中生成测试用例 (generate() 与 generate_n())

为数组程序生成测试用例有时是一个繁琐的过程。不过,STL(标准模板库)中的 INLINECODEbd739791 和 INLINECODE303dc1a3 函数可以非常方便地用随机值填充数组。

  • generate()

INLINECODE698515d1 函数会将生成器函数 INLINECODE7e54cd86 生成的随机值赋给范围 [begin, end) 内的元素。请注意,范围包含 begin,但不包含 end。

下面的代码演示了 generate 的实现:

CPP

// C++ program to demonstrate generate function in STL
#include      
using namespace std;

// function to generate random numbers in range [0-999] :
int randomize() 
{   
    return (rand() % 1000); 
}

int main () 
{
  // for different values each time we run the code
  srand(time(NULL)); 
  
  vector vect(10); // declaring the vector

  // Fill all elements using randomize()
  generate(vect.begin(), vect.end(), randomize);

  // displaying the content of vector
  for (int i=0; i<vect.size(); i++)
     cout << vect[i] << " " ;
  
  return 0;
}

输出结果:

832 60 417 710 487 260 920 803 576 58

注意:由于使用了 INLINECODEaaf51123,我们每次运行代码时的输出都会不同。如果我们移除 INLINECODEfe7f8714,那么每次运行代码时都会得到相同的随机数集合。

  • generate_n()

INLINECODE85e422f7 的作用与 INLINECODEf0fbb969 类似,但它只对从 begin 迭代器指向的元素开始的 n 个元素进行填充。

下面的代码演示了 generate_n 的工作原理:

CPP

// C++ program to demonstrate generate_n() function in STL
#include     
using namespace std;

// function to generate random numbers in range [0-999] :
int randomize() 
{   
    return (rand() % 1000); 
}

int main () 
{
  // for different values each time we run the code 
  srand(time(NULL)); 
  
  vector vect(10); // declaring the vector

  // Fill 6 elements from beginning using randomize()
  generate_n(vect.begin(), 6, randomize);

  // displaying the content of vector
  for (int i=0; i<vect.size(); i++)
    cout << vect[i] << " " ;
  
  return 0;
}

输出结果:

177 567 15 922 527 4 0 0 0 0

注意:在这里,同样因为 INLINECODE8b3345f5 的存在,每次运行代码时的输出都会不同。如果我们移除 INLINECODEb8bd561b,每次运行代码时都会得到相同的随机数集合。

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。如需转载,请注明文章出处豆丁博客和来源网址。https://shluqu.cn/43639.html
点赞
0.00 平均评分 (0% 分数) - 0