I am trying to create a set of n whole numbers in c++ and I was wondering is there is a more efficient way of doing it rather than the simple for loop as shown below
std::set<int> indices;
for(int i = 0; i < n; ++i){
indices.insert(i);
}
I tried googling but couldn't find the any answers. I feel like the incremental nature of the numbers being inserted should lead to a more efficient implementation.
If you want to be efficient you can leverage emplace_hint
. If the value to emplace should be emplaced right before the hint then it will happen in constant time instead of log N
.
std::set indices;
for (int i = 0; i < n; ++i)
{
indices.emplace_hint(indices.end(), i);
}
should be O(N)
instead of O(NlogN)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With