这是结合std :: generate_n和std :: back_inserter的正确方法吗? [英] Is this correct way to combine std::generate_n and std::back_inserter?
问题描述
在我的追求:)中,我想使用尽可能多的STL,我想知道是否可以将std :: generate和std :: back_inserter结合使用,以便我可以执行以下代码: / p>
In my quest :) to use as much of STL as I can I came to wonder is it possible to use std::generate and std::back_inserter combined so that I can do the same thing as the following code :
static const size_t nitems=1024*1024;
std::string mrbig;
for (size_t pos=0; pos<nitems; ++pos)
mrbig.push_back('a'+ (rand()%26));
我尝试过
std::generate_n(std::back_inserter(mrbig),nitems,[](){return 'a'+(rand()%26);});
似乎正常,但是我想确定我不会弄乱什么。
and it seems to work OK, but I would like to be sure Im not messing up something.
推荐答案
generate_n
要求其第一个参数满足 OutputIterator
,其中 back_insert_iterator
起作用(其 iterator_category
是 output_iterator_tag
)。
generate_n
requires that its first argument satisfy OutputIterator
, which back_insert_iterator
does (its iterator_category
is output_iterator_tag
).
您的代码可能存在的问题:
Potential issues with your code:
std::generate_n(std::back_inserter(mrbig),nitems,[](){return 'a'+(rand()%26);});
- 调用
mrbig.reserve(nitems)
会更有效率 - 您应使用 c ++ 03
std :: rand
或 c ++ 11uniform_int_distribution<>
从< random>
而不是 crand
。 - 括号之间的括号
()
对于不接受任何参数的lambda,lambda捕获和lambda主体是不必要的,尽管有些人喜欢它们。 - 不能保证在实现中字符集字母
az
连续块例如,EBCDIC中的,i
和j
不相邻。我相信唯一可移植的形式是在程序中存储字符串abcd ... xyz
并对其进行索引:如何编写一个 - Calling
mrbig.reserve(nitems)
would be more efficient - You should use c++03
std::rand
or c++11uniform_int_distribution<>
from<random>
instead of crand
. - The parentheses
()
between the lambda capture and lambda body are unnecessary for a lambda taking no arguments, although some people prefer them - It is not guaranteed that in implementation character set the letters
a-z
form a contiguous block; for example, in EBCDIC,i
andj
are not adjacent. I believe the only portable form is to store a string"abcd...xyz"
in your program and index into it: How can I write a single for loop running from a to z and A to Z in C?
这篇关于这是结合std :: generate_n和std :: back_inserter的正确方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!