Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the most efficient way to create an std::set of first n whole numbers? [duplicate]

Tags:

c++

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.

like image 495
Morpheus Avatar asked Dec 08 '22 13:12

Morpheus


1 Answers

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).

like image 78
NathanOliver Avatar answered Jun 01 '23 15:06

NathanOliver