Write a program using the C++ STL map container to implement simple management of fruit prices, including operations such as adding, printing, searching, modifying, and deleting. In this program, you create a map called `fruitPrices` to store the prices of different fruits. Then add some initial fruit prices, print the current fruit prices, and then allow the user to search for, modify, or delete a fruit price. Finally, print the updated fruit prices.
时间: 2024-03-01 15:52:57 浏览: 76
Sure, I can help you with that. Here's an example program that uses the C++ STL map container to implement a fruit price management system:
```c++
#include <iostream>
#include <string>
#include <map>
using namespace std;
int main() {
// Create a map to store fruit prices
map<string, double> fruitPrices;
// Add some initial fruit prices
fruitPrices["apple"] = 0.99;
fruitPrices["banana"] = 0.49;
fruitPrices["orange"] = 0.79;
// Print the current fruit prices
cout << "Current fruit prices:" << endl;
for (const auto& pair : fruitPrices) {
cout << "- " << pair.first << ": $" << pair.second << endl;
}
// Allow the user to search for, modify, or delete a fruit price
string fruitName;
cout << "Enter a fruit name to search for, modify, or delete: ";
cin >> fruitName;
// Check if the fruit exists in the map
auto it = fruitPrices.find(fruitName);
if (it != fruitPrices.end()) {
// Fruit exists, ask the user what operation to perform
char operation;
cout << "What would you like to do with " << fruitName << "?" << endl;
cout << " (S)earch for the price" << endl;
cout << " (M)odify the price" << endl;
cout << " (D)elete the price" << endl;
cin >> operation;
if (operation == 'S' || operation == 's') {
// Search for the fruit price
cout << fruitName << " costs $" << it->second << endl;
} else if (operation == 'M' || operation == 'm') {
// Modify the fruit price
double newPrice;
cout << "Enter the new price for " << fruitName << ": $";
cin >> newPrice;
fruitPrices[fruitName] = newPrice;
cout << "Price updated." << endl;
} else if (operation == 'D' || operation == 'd') {
// Delete the fruit price
fruitPrices.erase(it);
cout << "Price deleted." << endl;
} else {
// Invalid operation
cout << "Invalid operation." << endl;
}
} else {
// Fruit doesn't exist in the map
cout << "Sorry, " << fruitName << " is not in the list." << endl;
}
// Print the updated fruit prices
cout << "Updated fruit prices:" << endl;
for (const auto& pair : fruitPrices) {
cout << "- " << pair.first << ": $" << pair.second << endl;
}
return 0;
}
```
Here's an example interaction with the program:
```
Current fruit prices:
- apple: $0.99
- banana: $0.49
- orange: $0.79
Enter a fruit name to search for, modify, or delete: apple
What would you like to do with apple?
(S)earch for the price
(M)odify the price
(D)elete the price
m
Enter the new price for apple: $1.29
Price updated.
Updated fruit prices:
- apple: $1.29
- banana: $0.49
- orange: $0.79
```
I hope this helps! Let me know if you have any questions.
阅读全文