views:

75

answers:

1

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?

+3  A: 

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