有没有快速创建集合的方法?
目前我正在创建一个像这样的新集合:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
好吧,诚然有两行:)
Ok, admittedly two lines :)
在 C++0x 中,标准定义了 初始化器列表 作为对这种(尴尬的)结构。
现在容易多了:
标准库所需要的只是为 set: 声明以下构造函数
,我们所有的担忧都被一扫而光。
In C++0x the standard defines the Initializer List as an improvement for this kind of (awkward) construct.
It's much easier now:
All it took was for the standard library to declare the following constructor for set:
and all our worries were neatly swiped away.
您可以查看 Boost.Assign,它允许您编写内容例如 :
You can look into Boost.Assign, which allows you to write things such as :
您可能想看看 Boost.Assign:
http ://www.boost.org/doc/libs/1_44_0/libs/assign/doc/index.html
You might want to take a look at Boost.Assign:
http://www.boost.org/doc/libs/1_44_0/libs/assign/doc/index.html
如果您的初始数据位于某个容器中
std::some_container; a;
它有开始和结束迭代器,这是前向迭代器或最好的迭代器(它们应该重载operator++),那么你可以用这种方式创建新的集合。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.对于 A 的构造比
int
更昂贵的情况,这是 Moo-Juice 的答案的 C++0x 替代方案。Here's a C++0x alternative to Moo-Juice's answer for the case where construction of A is more expensive than for
int
.