开发者

How can I concisely initialize a safe collection in C++? [duplicate]

开发者 https://www.devze.com 2022-12-20 16:54 出处:网络
This question already has answers here: Closed 12 years ago. Possible Duplicate: C++: Easiest way to initialize an STL vector with hardcoded elements
This question already has answers here: Closed 12 years ago.

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?


Look into Boost.Assign, particularly list_of. It allows you to initialize a collection using code such as:

const vector<int> primes = list_of(2)(3)(5)(7)(11);
0

精彩评论

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