vector<Car> parkingLot;
时间: 2024-06-14 20:04:46 浏览: 172
`vector<Car> parkingLot;` 是一个C++中的容器,用于存储`Car`对象的集合。个`Car`对象代表一个车辆,包含了车辆的相关信息。
以下是一个示例,展示如何使用`vector<Car>`来管理停车场的车辆信息:
```cpp
#include <iostream>
#include <vector>
#include <algorithm>
struct Car {
std::string plateNumber;
int parkingTime;
};
bool compareCars(const Car& car1, const Car& car2) {
return car1.parkingTime > car2.parkingTime;
}
int main() {
std::vector<Car> parkingLot;
// 添加车辆信息到停车场
Car car1 = {"ABC123", 60};
Car car2 = {"DEF456", 120};
Car car3 = {"GHI789", 90};
parkingLot.push_back(car1);
parkingLot.push_back(car2);
parkingLot.push_back(car3);
// 输出停车场中的车辆数量
std::cout << "Total number of cars parking on campus: " << parkingLot.size() << std::endl;
// 找到停留时间最长的车辆
std::sort(parkingLot.begin(), parkingLot.end(), compareCars);
int longestParkingTime = parkingLot[0].parkingTime;
std::cout << "Longest parking time: " << longestParkingTime << std::endl;
// 输出停留时间最长的车辆的车牌号
std::cout << "Plate number(s) of car(s) with longest parking time: ";
for (const Car& car : parkingLot) {
if (car.parkingTime == longestParkingTime) {
std::cout << car.plateNumber << " ";
}
}
std::cout << std::endl;
return 0;
}
```
这段代码创建了一个`vector<Car>`类型的停车场,然后添加了三辆车辆的信息。通过排序和比较停留时间,找到了停留时间最长的车辆,并输出了其车牌号。
阅读全文