如何在C++中创建可重复的对象列表?

2024-10-03 00:29:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我开始从Python开始C++,所以我只是在浏览基本知识。当我试图创建一个包含对象的数组时,问题就出现了。在Python中,我将有一个具有coloryear属性的类Car:

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.")

试图在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.

但对这些车进行迭代确实很无趣,首先,这不起作用,其次,它们没有任何属性。我只是不明白,我想也许我错过了一些重要的事情,把它都搞错了,但是,我想我应该把这个解释清楚。你知道吗


Tags: andthe对象属性red数组carcars
3条回答

没有必要使用向量。您可以创建一个数组而不是std::vector。你知道吗

Car cars[] = {{"Red", 1986}, {"Black", 2007}, {"Blue", 1993}};
for (int i = 0; i < 3; ++i)
{
    std::cout << "The car has the color " << cars[i].color << " and is " 
        << (2014 - cars[i].year) << " years old." << std::endl;
}

希望它能编译。。。你知道吗

标准容器是可迭代的,如果不能使用C++ 11语法(如Anton Savin建议的),出于某种原因,可以使用更冗长的旧样式:

for (std::vector<Car>::const_iterator it=cars.begin(); it != cars.end(); ++it) {
    const Car & car = *it;
    std::cout << "The car has the color " << car.color << " and is " 
        << (2014 - car.year) << " years old." << std::endl;
}

尝试这个(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;
}

C++构建:

相关问题 更多 >