0

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?

Community
  • 1
  • 1
Evan Kroske
  • 4,506
  • 12
  • 40
  • 59
  • 4
    Lots of dupes including http://stackoverflow.com/questions/2236197/c-easiest-way-to-initialize-an-stl-vector-with-hardcoded-elements –  Feb 21 '10 at 20:05
  • Neil's right; apparently, I'm already using the easiest method (without Boost). – Evan Kroske Feb 21 '10 at 20:11

1 Answers1

3

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);
user200783
  • 13,722
  • 12
  • 69
  • 135