joejo
joejo

Reputation: 111

The Best way to insert a range of consecutive integers without boost::counting_iterator

What's the Best way to insert a range of consecutive integers without boost::counting_iterator.[c++]

    // Insert 1 to 9
    set<long> set1.insert(boost::counting_iterator<int>(1)
                          ,boost::counting_iterator<int>(10))

Upvotes: 0

Views: 108

Answers (2)

Jarod42
Jarod42

Reputation: 217348

You may use:

std::set<long> s;
long l = 0;
std::generate_n(std::inserter(s, s.end()), 9, [&]{ return ++l; });

or the simple loop:

std::set<long> s;
for (long i = 1; i != 10; ++i) {
    s.insert(i);
}

Upvotes: 0

Tony Delroy
Tony Delroy

Reputation: 106116

A for loop across the range calling insert works just fine and keeps the code simple to maintain.

Upvotes: 1

Related Questions