如何在C++中创建可迭代的对象列表?

PhP*_*PhP 1 c++ python arrays struct class

我开始从Python开始使用C++,所以我只是简单地介绍了基础知识.当我尝试在其中创建包含对象的数组时会出现问题.在Python我会与属性的类汽车coloryear:

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.")
Run Code Online (Sandbox Code Playgroud)

尝试在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.
Run Code Online (Sandbox Code Playgroud)

但迭代这些汽车确实无趣,至于一,这不起作用,其次,它们没有任何属性.我只是不明白,我想也许我已经错过了一些重要的事情并且把一切都弄错了,但是,我认为我只需要解释清楚而且很好.

Ant*_*vin 5

试试这个(C++ 11) - 看起来几乎像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;
}
Run Code Online (Sandbox Code Playgroud)

涉及的C++构造: