How can I concisely initialize a safe collection in C++? [duplicate]
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);
精彩评论