Efficiently initialise std::set with a sequence of numbers

后端 未结 5 1802
野的像风
野的像风 2020-12-31 01:29

An obvious (naive?) approach would be:

std::set s;
for (int i = 0; i < SIZE; ++i) {
    s.insert(i);
}

That\'s reasonable rea

5条回答
  •  傲寒
    傲寒 (楼主)
    2020-12-31 02:04

    This can be accomplished in a single line of code. The lambda capture can initialize the variable i to 0 and the mutable specifier allows i to be updated within the lambda function:

    generate_n( inserter( s, s.begin() ), SIZE, [ i=0 ]() mutable { return i++; });
    

提交回复
热议问题