基于C++的冰箱管理实例
以下是一些基于C++的冰箱管理实例示例,涵盖不同功能场景,每个示例聚焦特定实现点,代码可直接扩展或整合到项目中。
示例1:基础冰箱类定义
class Refrigerator {
private:int capacity;std::vector<std::string> items;
public:Refrigerator(int cap) : capacity(cap) {}void addItem(const std::string& item);void removeItem(const std::string& item);void displayItems() const;
};
示例2:添加物品并检查容量
void Refrigerator::addItem(const std::string& item) {if (items.size() >= capacity) {std::cerr << "Error: Fridge is full!" << std::endl;} else {items.push_back(item);}
}
示例3:移除指定物品
void Refrigerator::removeItem(const std::string& item) {auto it = std::find(items.begin(), items.end(), item);if (it != items.end()) {items.erase(it);} else {std::cerr << "Item not found." << std::endl;}
}
示例4:温度控制模块
class TemperatureController {
private:float currentTemp;
public:void setTemperature(float temp) {currentTemp = temp;}float getTemperature() const {return currentTemp;}
};
示例5:过期物品检测
struct FoodItem {std::string name;std::string expiryDate;
};bool isExpired(const FoodItem& item, const std::string& currentDate) {return item.expiryDate < currentDate;
}
示例6:使用文件保存库存
void saveToFile(const std::vector<std::string>& items, const std::string& filename) {std::ofstream file(filename);for (const auto& item : items) {file << item << "\n";}
}
示例7:多冰箱管理
std::map<std::string, Refrigerator> fridgeMap;
fridgeMap["Kitchen"] = Refrigerator(100);
fridgeMap["Garage"] = Refrigerator(50);
示例8:智能补货提醒
void checkLowStock(const std::vector<std::string>& items, int threshold) {if (items.size() < threshold) {std::cout << "ALERT: Low stock! Please refill." << std::endl;}
}
示例9:能耗统计
class EnergyMonitor {
private:float powerConsumption;
public:void updateConsumption(float watts) {powerConsumption += watts;}
};
示例10:门开关状态检测
class DoorSensor {
private:bool isOpen;
public:void doorOpened() { isOpen = true; }void doorClosed() { isOpen = false; }bool status() const { return isOpen; }
};
示例11:多线程温度监控
std::thread tempThread([]() {while (true) {monitorTemperature();std::this_thread::sleep_for(std::chrono::minutes(10));}
});
示例12:网络远程控制
class RemoteController {
public:void sendCommand(const std::string& cmd) {// 模拟网络请求std::cout << "Sending command: " << cmd << std::endl;}
};
示例13:异常处理机制
try {fridge.addItem("Milk");
} catch (const std::exception& e) {std::cerr << "Operation failed: " << e.what() << std::endl;
}
示例14:物品分类统计
std::map<std::string, int> countByCategory(const std::vector<FoodItem>& items) {std::map<std::string, int> counts;for (const auto& item : items) {counts[item.category]++;}return counts;
}
示例15:生成库存报告
每个示例可根据实际需求进一步扩展,例如添加序列化、多语言支持或硬件交互层。
C++的文件流库fstream
可以轻松读取文本
读取文件内容
使用C++的文件流库fstream
可以轻松读取文本文件内容。以下代码展示了如何打开并读取一个文本文件:
#include <iostream>
#include <fstream>
#include <string>int main() {std::ifstream file("example.txt");std::string line;if (file.is_open()) {while (std::getline(file, line)) {std::cout << line << '\n';}file.close();} else {std::cerr << "Unable to open file\n";}return 0;
}
逐行处理文本
对于英语文本处理,通常需要逐行读取并分析。以下代码演示了如何读取文件中的每一行并计算行数:
#include <iostream>
#include <fstream>
#include <string>int main() {std::ifstream file("english_text.txt");std::string line;int lineCount = 0;while (std::getline(file, line)) {lineCount++;std::cout << "Line " << lineCount << ": " << line << '\n';}std::cout << "Total lines: " << lineCount << '\n';return 0;
}
单词分割
将英语句子分割成单词是常见的需求。以下代码使用字符串流和空格作为分隔符来分割单词:
#include <iostream>
#include <sstream>
#include <vector>
#include <string>int main() {std::string sentence = "This is an example sentence for word splitting";std::istringstream iss(sentence);std::vector<std::string> words;std::string word;while (iss >> word) {words.push_back(word);}for (const auto& w : words) {std::cout << w << '\n';}return 0;
}
单词计数
统计文本中单词出现的频率是文本分析的基础。以下代码展示了如何计算每个单词的出现次数:
#include <iostream>
#include <map>
#include <string>
#include <sstream>int main() {std::string text = "hello world hello cpp world programming";std::istringstream iss(text);std::map<std::string, int> wordCount;std::string word;while (iss >> word) {wordCount[word]++;}for (const auto& pair : wordCount) {std::cout << pair.first << ": " << pair.second << '\n';}return 0;
}
正则表达式匹配
使用正则表达式可以更灵活地匹配英语文本模式。以下代码展示了如何使用正则表达式匹配特定模式的单词:
#include <iostream>
#include <regex>
#include <string>int main() {std::string text = "The quick brown fox jumps over the lazy dog";std::regex pattern("\\b\\w{4}\\b"); // 匹配4字母单词std::smatch matches;while (std::regex_search(text, matches, pattern)) {for (auto match : matches) {std::cout << match << '\n';}text = matches.suffix().str();}return 0;
}
大小写转换
处理英语文本时经常需要转换大小写。以下代码展示了如何将文本转换为全大写或全小写:
#include <iostream>
#include <algorithm>
#include <string>int main() {std::string text = "Hello World";// 转换为大写std::transform(text.begin(), text.end(), text.begin(), ::toupper);std::cout << text << '\n';// 转换为小写std::transform(text.begin(), text.end(), text.begin(), ::tolower);std::cout << text << '\n';return 0;
}
标点符号移除
清理文本中的标点符号是文本预处理的重要步骤。以下代码展示了如何移除字符串中的标点符号:
#include <iostream>
#include <string>
#include <cctype>int main() {std::string text = "Hello, World! This is a test.";std::string result;for (char c : text) {if (!std::ispunct(c)) {result += c;}}std::cout << result << '\n';return 0;
}
句子分割
将段落分割成句子是自然语言处理的基础。以下代码展示了基于句号、问号和感叹号分割句子:
#include <iostream>
#include <vector>
#include <string>int main() {std::string paragraph = "Hello! How are you? I'm fine. Thanks.";std::vector<std::string> sentences;size_t start = 0;size_t end = paragraph.find_first_of(".!?");while (end != std::string::npos) {sentences.push_back(paragraph.substr(start, end - start + 1));start = end + 2; // 跳过标点和空格end = paragraph.find_first_of(".!?", start);}for (const auto& s : sentences) {std::cout << s << '\n';}return 0;
}
词干提取
词干提取是文本规范化的重要步骤。以下代码展示了简单的词干提取方法(Porter算法简化版):
#include <iostream>
#include <string>
#include <algorithm>std::string stemWord(const std::string& word) {if (word.length() >= 5) {if (word.substr(word.length() - 3) == "ing") {return word.substr(0, word.length() - 3);}if (word.substr(word.length() - 2) == "ed") {return word.substr(0, word.length() - 2);}}return word;
}int main() {std::string word = "running";std::cout << stemWord(word) << '\n'; // 输出: runnreturn 0;
}
停用词移除
移除常见停用词可以提高文本分析质量。以下代码展示了如何过滤停用词:
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>int main() {std::vector<std::string> stopwords = {"the", "a", "an", "in", "on", "at"};std::vector<std::string> words = {"the", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog"};std::vector<std::string> filtered;for (const auto& word : words) {if (std::find(stopwords.begin(), stopwords.end(), word) == stopwords.end()) {filtered.push_back(word);}}for (const auto& word : filtered) {std::cout << word << " ";}return 0;
}
拼写检查
基本的拼写检查可以通过字典比对实现。以下代码展示了简单的拼写检查:
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>int main() {std::vector<std::string> dictionary = {"hello", "world", "cpp", "programming"};std::string word = "helo";if (std::find(dictionary.begin(), dictionary.end(), word) == dictionary.end()) {std::cout << word << " might be misspelled.\n";} else {std::cout << word << " is spelled correctly.\n";}return 0;
}