An obvious (naive?) approach would be:
std::set<int> s;
for (int i = 0; i < SIZE; ++i) {
s.insert(i);
}
That's reasonable readable, but from what I understand, not optimal since it involves repeatedly searching for the insertion position and does not take advantage of the fact that the input sequence is already sorted.
Is there a more elegant/efficient (or a de facto) way of initialising an std::set
with a sequence of numbers?
Or, more generically, how does one efficiently insert an ordered list of entries into a collection?
Update:
Looking through the docs, I've just noticed the constructor that accepts an iterator to indicate the position for insertion:
iterator insert ( iterator position, const value_type& x );
Which means this would be more efficient:
std::set<int> s;
std::set<int>::iterator it = s.begin();
for (int i = 0; i < SIZE; ++i) {
it = s.insert(it, i);
}
That looks reasonably, but I'm still open to more suggestions.