Reputation: 79615
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
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
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
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
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
Reputation: 38825
int myints[]= {10,20,30,40,50};
std::set<int> mySet(myints, myints + 5);
Ok, admittedly two lines :)
Upvotes: 22
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