当前位置: 首页 > news >正文

C++冰箱管理实战代码

基于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;
}

N-gram生成

http://www.dtcms.com/a/311296.html

相关文章:

  • 【Flutter3.8x】flutter从入门到实战基础教程(八):公共state的集中管理机制
  • 人工智能开发框架 08. MNIST手写数字识别任务(一)
  • Java基础——实现图书管理系统交互功能
  • Hyper-V + Centos stream 9 搭建K8s集群(一)
  • HTTP数据请求
  • 涉水救援机器人cad【12张】三维图+设计书明说
  • 【网络原理】HTTP协议(一)
  • 【LeetCode 热题 100】(四)子串
  • leetcode热题——组合
  • 【10】VisionMaster入门到精通——脚本打印日志到本地(获取条码和二维码信息)
  • React ahooks——副作用类hooks之useThrottleEffect
  • 易华路副总经理兼交付管理中心部门经理于江平受邀PMO大会主持人
  • Cursor 与 VS Code 与 GitHub Copilot 的全面比较
  • 高性能MCP服务器架构设计:并发、缓存与监控
  • 【MySQL集群架构与实践5】使用Docker实现水平分片
  • 在医疗设备高精度需求下,猎板印制线路板的定制化服务与实践
  • 开源在线客服系统Chatwoot配置文件
  • 西门子 G120 变频器全解析:从认知到参数设置
  • 进阶向:自动化天气查询工具(API调用)
  • 江协科技STM32 13-1 PWR电源控制
  • 【DL学习笔记】DL入门指南
  • 攀爬识别场景误报率↓77%:陌讯动态特征融合算法实战解析
  • C++ 模板初阶
  • Oracle 11g RAC集群部署手册(二)
  • OAuth 2.0 详解:现代授权的核心协议
  • 《机器学习数学基础》补充资料:泰勒定理与余项
  • webpack面试题及详细答案80题(61-80)
  • linux-process-control
  • Linux自主实现shell
  • Maven - 并行安全无重复打包构建原理揭秘