Efficiently initialise std::set with a sequence of numbers

后端 未结 5 1801
野的像风
野的像风 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 01:54

    The right iterator to use as the hint has changed between C++03 and C++11. With C++03, you want to use the position of the previous item (just as you and most of the replies have shown).

    In C++11, you want to use the iterator to the item immediately after the one you're about to insert. When you're inserting in order, this makes things a bit simpler: you always use your_container.end():

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

    You can, of course, use an algorithm (e.g., std::iota) or iterator (e.g., boost::counting_iterator, as @pmr already mentioned) to generate your values, but as far as the insertion itself goes, for a current implementation you want to use .end() as the hint, rather than the iterator returned by the previous insertion.

提交回复
热议问题