Amir Rachum
Amir Rachum

Reputation: 79615

Is there a quick way to create a set?

Currently I'm creating a new set like this:

    std::set<A> s;
    s.insert(a1);
    s.insert(a2);
    s.insert(a3);
    ...
    s.insert(a10);

Is there a way to create s in one line?

Upvotes: 15

Views: 24320

Answers (6)

Matthieu M.
Matthieu M.

Reputation: 299760

In C++0x the standard defines the Initializer List as an improvement for this kind of (awkward) construct.

It's much easier now:

std::set<int> set = {10, 20, 30, 40, 50};

All it took was for the standard library to declare the following constructor for set:

template <typename Value, typename Compare, typename Allocator>
set<Value, Compare, Allocator>::set(std::initializer_list<Value> list);

and all our worries were neatly swiped away.

Upvotes: 16

Mihran Hovsepyan
Mihran Hovsepyan

Reputation: 11088

If your initial data is in some container std::some_container<A> a; which has begin and end iterators, and this are forward iterators or best ones (they just should have operator++ overloaded) then you can make new set this way.

std::set<A> s(a.begin(), a.end());

Upvotes: 5

Steve Townsend
Steve Townsend

Reputation: 54138

Here's a C++0x alternative to Moo-Juice's answer for the case where construction of A is more expensive than for int.

int myints[]= {10,20,30,40,50};
size_t total(sizeof(myints) / sizeof(int));

auto begin(std::make_move_iterator(myints));
auto end(std::make_move_iterator(myints + total));

std::set<int> mySet(begin, end);

Upvotes: 4

icecrime
icecrime

Reputation: 76745

You can look into Boost.Assign, which allows you to write things such as :

const std::list<int> primes = boost::assign::list_of(2)(3)(5)(7)(11);

Upvotes: 9

Moo-Juice
Moo-Juice

Reputation: 38825

int myints[]= {10,20,30,40,50};
std::set<int> mySet(myints, myints + 5);

Ok, admittedly two lines :)

Upvotes: 22

Stuart Golodetz
Stuart Golodetz

Reputation: 20616

You might want to take a look at Boost.Assign:

http://www.boost.org/doc/libs/1_44_0/libs/assign/doc/index.html

Upvotes: 5

Related Questions