Search code examples
c++insertintegerrangestdset

How to efficiently insert a range of consecutive integers into a std::set?


In C++, I have a std::set that I would like to insert a range of consecutive integers. How can I do this efficiently, hopefully in O(n) time where n is the length of the range?

I'm thinking I'd use the inputIterator version of std::insert, but am unclear on how to build the input iterator.

std::set<int> mySet;

// Insert [34 - 75):
mySet.insert(inputIteratorTo34, inputIteratorTo75);

How can I create the input iterator and will this be O(n) on the range size?


Solution

  • Taking the hint provided by aksham, I see the answer is:

    #include <boost/iterator/counting_iterator.hpp>
    
    std::set<int> mySet;
    
    // Insert [34 - 75):
    mySet.insert(boost::counting_iterator<int>(34),
                 boost::counting_iterator<int>(75));