如何在 C++ 中简洁地初始化安全集合?
我现在正在学习 C++,我正在寻找一种方法来快速轻松地初始化每个元素具有不同值的“安全”集合(如向量)。我习惯了 Python 简洁的列表/元组初始化,并且我想知道 C++ 中是否有等效的语法技巧或集合类型。
例如,如果我想在 Python 中初始化唯一 Payment 对象的列表,我可以这样做:
payments = [Payment(10, 2), Payment(20, 4), Payment(30, 6)]
但是,为了在 C++ 中初始化 Payment 结构向量,我需要编写如下内容:
Payment tempPayments[] = {
{10, 2},
{20, 4},
{30, 6}
};
vector<Payment> examplePayments(tempPayments, tempPayments +
sizeof(tempPayments) / sizeof(Payment));
有没有更简单的方法初始化具有独特结构的向量,还是其他更方便的安全集合?
Possible Duplicate:
C++: Easiest way to initialize an STL vector with hardcoded elements
I'm learning C++ right now, and I'm looking for a way to quickly and easily initialize a "safe" collection (like a vector) with different values for each element. I'm accustomed to Python's concise list/tuple initializations, and I want to know if there's an equivalent syntax trick or collection type in C++.
For example, if I want to initialize a list of unique Payment objects in Python, I can do this:
payments = [Payment(10, 2), Payment(20, 4), Payment(30, 6)]
However, in order to initialize a vector of Payment structures in C++, I need to write something like this:
Payment tempPayments[] = {
{10, 2},
{20, 4},
{30, 6}
};
vector<Payment> examplePayments(tempPayments, tempPayments +
sizeof(tempPayments) / sizeof(Payment));
Is there an easier way to initialize a vector with unique structures, or another safe collection that's more convenient?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
查看Boost.Assign,特别是< a href="http://www.boost.org/doc/libs/1_42_0/libs/assign/doc/index.html#list_of" rel="nofollow noreferrer">list_of。它允许您使用以下代码初始化集合:
Look into Boost.Assign, particularly list_of. It allows you to initialize a collection using code such as: