Skip to content

Instantly share code, notes, and snippets.

@bdonlan
Created September 23, 2011 03:48
Show Gist options
  • Save bdonlan/1236709 to your computer and use it in GitHub Desktop.
Save bdonlan/1236709 to your computer and use it in GitHub Desktop.
// Simple approach. Requires that you invoke as gen_array<int>(generator_func) for example
// Requires C++0x for std::function; boost's boost::function will also work on all compilers
template<typename ArrayElement>
std::vector<ArrayElement> gen_array(std::function<ArrayElement()> gen)
{
int len = gen_int() % 100;
std::vector<ArrayElement> vec;
vec.reserve(len);
for (size_t i = 0; i < len; i++)
vec.push_back(gen());
return vec;
}
// Fancy approach. Probably slightly faster. Requires C++0x for result_of type trait (and >> template closing ;)
// Invoked simply as gen_array(some_func)
template<typename Generator>
std::vector<std::result_of<Generator()>> gen_array(Generator gen)
{
int len = gen_int() % 100;
std::vector<std::result_of<Generator()>> vec;
vec.reserve(len);
for (size_t i = 0; i < len; i++)
vec.push_back(gen());
return vec;
}
/* One of the nice things about this is you can use lambda functions as well. For example: */
std::vector<int> testarr = gen_array( []{ gen_range(0, 42); } );
/* Note: Lambda functions are a C++0x feature.
* Workaround libraries are available on older compilers, although the syntax is uglier - eg: */
std::vector<int> testarr = gen_array( boost::bind(gen_range, 0, 42) );
/* You can also use parameter overloading to provide defaults: */
template<typename Generator, typename LengthFunc>
std::vector<std::result_of<Generator()>> gen_array(Generator gen, LengthFunc lf) {
int len = lf();
// ...
}
template<typename Generator>
std::vector<std::result_of<Generator()>> gen_array(Generator gen, int minlen, int maxlen) {
return gen_array(gen, gen_int(minlen, maxlen));
}
template<typename Generator>
std::vector<std::result_of<Generator()>> gen_array(Generator gen) {
return gen_array(gen, 0, 100);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment