开发者

Is there a quick way to create a set?

开发者 https://www.devze.com 2023-01-25 02:48 出处:网络
Currently I\'m creating a new set like this: s开发者_运维技巧td::set<A> s; s.insert(a1); s.insert(a2);

Currently I'm creating a new set like this:

    s开发者_运维技巧td::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?


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

Ok, admittedly two lines :)


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.


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);


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

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


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());


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);
0

精彩评论

暂无评论...
验证码 换一张
取 消