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

  • A+
Category:Languages

This question already has an answer here:

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

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: