在计算最近N次购买的平均价格之前,我们可以对日期进行排序,以便选择日期最大的N个购买记录。以下是修改后的代码:
#include <iostream>
#include <string>
#include <unordered_map>
#include <algorithm> // 添加头文件以使用std::sort函数
using namespace std;
// 购买记录结构体
struct Purchase {
string date;
string product;
double price;
};
// 单链表节点结构体
struct Node {
Purchase purchase;
Node* next;
Node(const Purchase& p) : purchase(p), next(nullptr) {}
};
// 比较函数,用于日期从大到小排序
bool compareDate(const Purchase& p1, const Purchase& p2) {
return p1.date > p2.date;
}
// 计算最近N次购买的平均价格
double calculateAveragePrice(Node* head, int N) {
double sum = 0.0;
int count = 0;
Node* current = head;
while (current != nullptr && count < N) {
sum += current->purchase.price;
count++;
current = current->next;
}
if (count > 0) {
return sum / count;
} else {
return 0.0; // 没有足够的购买记录,返回0.0
}
}
int main() {
int m, n;
cin >> m >> n;
unordered_map<string, Node*> productMap; // 商品名和对应链表头指针的哈希映射
for (int i = 0; i < m; i++) {
string date, product;
double price;
cin >> date >> product >> price;
Purchase purchase{date, product, price};
if (productMap.find(product) == productMap.end()) {
Node* newNode = new Node(purchase);
productMap[product] = newNode;
} else {
Node* newNode = new Node(purchase);
newNode->next = productMap[product];
productMap[product] = newNode;
}
}
// 对购买记录链表进行日期从大到小排序
for (auto& pair : productMap) {
string productName = pair.first;
Node* head = pair.second;
vector<Purchase> purchases; // 用于存储购买记录的临时向量
Node* current = head;
while (current != nullptr) {
purchases.push_back(current->purchase);
current = current->next;
}
sort(purchases.begin(), purchases.end(), compareDate); // 对购买记录进行排序
// 将排序后的记录重新连接成链表
Node* newHead = nullptr;
for (const auto& purchase : purchases) {
Node* newNode = new Node(purchase);
newNode->next = newHead;
newHead = newNode;
}
pair.second = newHead; // 更新哈希映射中的链表头指针
}
// 计算最近N次购买的平均价格并输出结果
for (auto& pair : productMap) {
string productName = pair.first;
Node* head = pair.second;
double avgPrice = calculateAveragePrice(head, n);
cout << avgPrice << endl;
// 释放动态分配的内存
Node* current = head;
while (current != nullptr) {
Node* temp = current;
current = current->next;
delete temp;
}
}
return 0;
}
在这个修改后的代码中,我们添加了一个比较函数compareDate(),用于对购买记录按日期从大到小进行排序。然后,在构建哈希映射时,我们将购买记录存储在临时向量中,并使用std::sort()函数对其进行排序。最后,我们将排序后的记录重新连接成链表,并更新哈希映射中的链表头指针。这样就可以根据日期从大到小选择最近N次购买记录并计算平均价格。
内容由零声教学AI助手提供,问题来源于学员提问




