-2

Ok , so this is a short query.

I have a Set container say a ;

c=5 , d= 42 are integers.

I want to insert all integers from 5 to 42 in the set without using the for loop.

How can i do this??

Finally a should look like {5,6,7.......,42}

Ayush Goyal
  • 91
  • 1
  • 9
  • 4
    http://en.cppreference.com/w/cpp/algorithm/iota and http://en.cppreference.com/w/cpp/container/set/insert overload five. – user4581301 Feb 07 '17 at 20:11
  • The best way to do this is with a for loop. Why would you request some other way? – Benjamin Lindley Feb 07 '17 at 20:16
  • What are the reasons against a `for` loop? – Thomas Matthews Feb 07 '17 at 20:16
  • @BenjaminLindley Actually this is a part of a problem i am solving , so i need to bring down the complexity of my code , hence i thought there may be an efficient method to create intervals using set – Ayush Goyal Feb 07 '17 at 20:19
  • Your going to have a loop. Whether you abstract that away with a function or not is your call but you need to do N operations and to do that you use a loop. – NathanOliver Feb 07 '17 at 20:20
  • @NathanOliver Ohh , guess i have to rethink the Algo then , thanks btw :-) – Ayush Goyal Feb 07 '17 at 20:21
  • @AyushGoyal I think you need a vectorization/parallelization library to bring down the complexity of your code. – Rama Feb 07 '17 at 20:34
  • 1
    Possible duplicate of [How to efficiently insert a range of consecutive integers into a std::set?](http://stackoverflow.com/questions/18295333/how-to-efficiently-insert-a-range-of-consecutive-integers-into-a-stdset) – Rama Feb 07 '17 at 20:56

1 Answers1

4

Something like this:

#include <algorithm>
#include <iostream>
#include <iterator>
#include <set>

template<class OutputIterator, class T>
OutputIterator iota_rng(OutputIterator first, T low, T high)
{
        return std::generate_n(first, high - low, [&, value = low]() mutable { return value++; });
} 

int main()
{
    std::set<int> s;
    iota_rng(std::inserter(s, s.begin()), 5, 43);
    for (auto elem : s) {
        std::cout << elem << ", ";    
    }
}

Live Example

In the range-v3 library (proposed as a technical specification) you can write it even more concisely as:

#include <range/v3/all.hpp>
#include <iostream>
#include <set>

int main()
{
    std::set<int> s = ranges::view::iota(5, 43);
    for (auto elem : s) {
        std::cout << elem << ", ";    
    }
}

Live Example

TemplateRex
  • 67,479
  • 19
  • 160
  • 290