How does one create iterateable lists of objects in C++?
Question: I'm starting out C++ coming from Python, so I'm pretty much just scrolling
through the basics. Problem occurs when I try to make an array with objects in
it. In Python I would have a class Car with the attributes `color` and `year`:

    
    
    myCars = [Car("Red", 1986), Car("Black", 2007), Car("Blue", 1993)]
    # and then going through the cars:
    for car in myCars:
    print("The car has the color " + car.color + " and is " + (2014 - car.year) + " years old.")
    

Trying to do something similar in C++:

    
    
    struct Car {
        string color;
        int year;
    };
    
    int cars[3] = {Car cars[0], Car cars[1], Car cars[2]}
    //EDIT: I wrote bilar but I meant cars.
    

but it is indeed uninteresting to iterate over these cars, as for one, this
doesn't work, and secondly, they doesn't have any attributes. I just don't
understand, I think maybe I've missed something important and got it all
wrong, but then, I reckon I just gotta have this explained clean and nice.


Answer: Try this (C++11) - looks almost like Python:

    
    
    std::vector<Car> cars = {{"Red", 1986}, {"Black", 2007}, {"Blue", 1993}};
    for (const Car& car : cars) {
        std::cout << "The car has the color " << car.color << " and is " 
            << (2014 - car.year) << " years old." << std::endl;
    }
    

C++ constructs involved:

  * [`std::vector`](http://en.cppreference.com/w/cpp/container/vector)
  * [list initialization](http://en.cppreference.com/w/cpp/language/list_initialization)
  * [range `for` loop](http://en.cppreference.com/w/cpp/language/range-for)

