2014-11-21 26 views
1

我开始从Python来的C++,所以我几乎只是滚动浏览基础知识。当我尝试使用其中的对象创建一个数组时,会发生问题。在Python我会与属性coloryear一类车:如何在C++中创建可迭代的对象列表?

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. 

,但它确实是无趣遍历这些车,作为一,这不起作用,其次,他们没有任何属性。我只是不明白,我想也许我已经错过了一些重要的东西,并且弄错了所有的错误,但是我认为我必须把这个解释得干干净净,很好。

+0

当您使用'INT比拉尔[3]'你正在创建一个整数数组。你需要使用'Car bilar [3]'。 – IanAuld 2014-11-21 19:07:36

+0

@IanAuld这听起来合乎逻辑,我想知道这些类型......但是,那么如何将任何值赋给'car [x]'?我是否必须为每个任务写一个'car [2] .color =“Red”'等等。 – PhP 2014-11-21 19:21:19

+0

您可以像使用Python一样在C++中创建构造函数,以便您可以执行'Car my_car = Car('Red','2007');'。我自己是一个Python人,我的C++有点生疏,所以我不记得如何去做。 – IanAuld 2014-11-21 19:23:56

回答

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; 
} 

C++构建参与:

+0

'const'是什么意思,这是否意味着我正在使用一个向量,这到底意味着什么?另外,我假设':'有''in'的意思? – PhP 2014-11-21 19:25:14

+0

关于':':http://en.cppreference.com/w/cpp/language/range-for – 2014-11-21 19:42:58

+1

'const'意味着'car'应该是不可变的。而一个'std :: vector'应该与Python列表基本上没有区别。 – 2014-11-21 19:44:14

1

标准容器是可迭代的,如果你不能使用C++语法11(作为一个由安东萨建议)由于某种原因,你可以使用更详细的老式:

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; 
} 
1

它`没有必要使用矢量。你可以创建一个数组而不是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; 
} 

希望它`编译...

相关问题