有没有快速创建集合的方法?

发布于 2024-10-03 05:52:33 字数 218 浏览 0 评论 0原文

目前我正在创建一个像这样的新集合:

    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?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

山田美奈子 2024-10-10 05:52:34
int myints[]= {10,20,30,40,50};
std::set<int> mySet(myints, myints + 5);

好吧,诚然有两行:)

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

Ok, admittedly two lines :)

十六岁半 2024-10-10 05:52:34

在 C++0x 中,标准定义了 初始化器列表 作为对这种(尴尬的)结构。

现在容易多了:

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

标准库所需要的只是为 set: 声明以下构造函数

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

,我们所有的担忧都被一扫而光。

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.

揽清风入怀 2024-10-10 05:52:34

您可以查看 Boost.Assign,它允许您编写内容例如 :

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

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);
温柔戏命师 2024-10-10 05:52:34

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());
生寂 2024-10-10 05:52:34

对于 A 的构造比 int 更昂贵的情况,这是 Moo-Juice 的答案的 C++0x 替代方案。

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

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);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文