我试图解决以下问题:
编写一个程序,它将从用户那里得到
“不可达的城市!”
。现在的问题是,我写了一个代码,找到了这样的车次,但不是所有的车次,它不能显示所有的车次去想要的目的地点。
即。 如果我输入以下数据:
3
Chicago I-789
Chicago J-159
Chicago A-465
Chicago
它只显示最后一次列车号码A-465
,而正确答案是:I-789 J-159 A-465
#include <iostream>
#include <string>
using namespace std;
class MyClass {
public:
string city;
string number;
};
int main() {
int N;
cin >> N;
MyClass myObj;
for (int i=0; i<N; i++){
cin>>myObj.city;
cin>>myObj.number;
}
string destination;
cin >> destination;
if(myObj.city==destination){
cout << myObj.number;
}
else{
cout << "Unreachable city!";
}
return 0;
}
首先,myObj不是一个好名字,让我们把它改成一个空的目的地列表。
#include <vector>
...
vector <MyClass> destinations;
接下来,将每个新值推入向量。 为此,最好有一个设置值的构造函数。 构建一个没有值的目标是没有意义的。
MyClass(string _c, string _n) : city(_c), number(_n) {};
...
string city, number;
cin >> city;
cin >> number;
destinations.pushback(MyClass(city, number));
现在,您可以编写循环来遍历向量,寻找所需的数据。
关于您的评论:
C++比Python难多了。
编程语言只是工具。 你用它们来解决问题。 如果你不知道如何使用一个工具,你就不能解决问题。 你的电脑是一个工具,如果你不知道如何操作它,你就不能做作业。 这并不意味着电脑很难使用。 同样,C++是一个工具,如果你不了解它,并不意味着它很难。
让我们进入问题。
该程序应该找到并显示所有的列车数量,这些列车去往想要的目的地。 如果没有这样的火车,程序必须显示“无法到达的城市!”。
让我们把它分解
你的代码的问题是只有“一列火车”:
MyClass myObj; //one object only
每次从用户那里获取输入时,都要覆盖它的值。
那么,你能做些什么来解决这个问题呢? 在编程中,当我们想要存储同一个对象的多个值时,我们通常创建一个数组。 数组只是一种类型的值的集合。 示例:
int myarray[5]; //can store 5 "int" values
//size is given inside the [] (square brackets)
数组索引从0
开始。 我们可以将值存储在数组中,如下所示:
cin >> myarray[0]; //take input from user and store it into the "first" place in our array
cin >> myarray[1]; //store in the "second" place
cin >> myarray[4]; //store in the "last" place
cin >> myarray[5]; //WRONG! Don't do this. It will result in errors and bugs!! (Undefined Behaviour)
也可以直接存储值:
int myarray[5] = {1, 2, 3, 4, 5};
cout << myarray[3]; // prints "4"
这一切都很好,但是数组有一个小问题。 在创建数组之前,我们必须知道数组的“大小”。
int N;
cin >> N;
int array[N]; //WRONG, even it works, this is wrong.
那么,我们该怎么办呢? 我们不可能总是知道我们想要的对象的数量。 不用担心,因为C++为我们提供了一个很好的容器:std::vector
,它可以用来解决这个问题。
#include <vector> // you need this for vector
int N;
cin >> N;
std::vector <int> myvector(N); //vector of size N
//access the values as you would with the array
myvector[0] = 10;
myvector[5] = 9; //WRONG.
注意,我不会直接给你解决方案,但我会给你指路,给你工具。 这是你的问题,这是你的挑战,如果你尝试,解决问题是相当容易的。
所以我们学习了向量和数组。 接下来,您可能想知道如何为您的类型创建vector。 简单:
//create a vector, with size = N
vector <MyClass> Trains (N);
//take input from user
for (int i=0; i<N; i++){
cin >> Trains[i].city;
cin >> Trains[i].number;
}
最后一部分,将相当相似。 您需要一个循环,然后遍历向量中的所有值以找到您想要的“目的地”。
你应该从命名你的对象和变量开始,以一种对你来说容易和自然的方式来思考你的问题。 例如:
class MyClass
这并不能告诉任何人,任何关于你的课或者你想用它做什么。 还有什么更好的名字呢? 看问题,我建议用train
:
class Train {};
问题还告诉我们,每趟列车都有一个“目的地城市”和一个“车次”。 我们可以重构train
类以包含以下内容:
class Train {
public:
string destination;
string number;
};