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.pswp.cn/web/91722.shtml
繁體地址,請注明出處:http://hk.pswp.cn/web/91722.shtml
英文地址,請注明出處:http://en.pswp.cn/web/91722.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

【Python】【數據分析】Python 數據分析與可視化:全面指南

目錄1. 環境準備2. 數據處理與清洗2.1 導入數據2.2 數據清洗示例&#xff1a;處理缺失值示例&#xff1a;處理異常值2.3 數據轉換3. 數據分析3.1 描述性統計3.2 分組分析示例&#xff1a;按年齡分組計算工資的平均值3.3 時間序列分析4. 數據可視化4.1 基本繪圖示例&#xff1a;…

【AI】AIService(基本使用與指令定制)

【AI】AIService(基本使用與指令定制) 文章目錄【AI】AIService(基本使用與指令定制)1. 簡介2. AIService2.1 引入依賴2.2 編寫AIService接口2.3 測試代碼3. 指令定制3.1 系統提示詞3.2 用戶提示詞1. 簡介 AIService可以被視為應用程序服務層的一個組件&#xff0c;提供對應的…

AAAI趕稿后的心得

總結 已經第三次和老師們一起趕稿了&#xff0c;但是還是紕漏重重&#xff0c;每次都被我的垃圾寫作給嚇到。每次都手忙腳亂找不到重點&#xff0c;唉&#xff0c;我大概這輩子都成為不了郭老師&#xff1a; 自己把故事先捋清楚&#xff1a; 所有的東西都要抽象出來&#xff0c…

書籍推薦算法研究

## 項目概述本項目是一個完整的書籍推薦系統第五版(Complete Book Recommendation System V5),采用混合推薦策略,能夠處理6種不同的用戶場景,提供智能化的書籍推薦服務。## 系統架構### 核心設計思路系統采用**混合推薦策略**,結合了以下幾種推薦算法:1. **協同過濾推薦…

工具自動生成Makefile

cmake 基礎 cmake主要是生成Makefile&#xff0c;以便工程管理&#xff0c;只需要編寫CMakeLists.txt安裝camkesudo apt install cmake 安裝cmake camke --version 查看cmake版本 sudo apt upgrade cmake 升級cmake源碼隔離 在工程文件下創建一個build文件&…

Java項目:基于SSM框架實現的校園活動資訊網管理系統【ssm+B/S架構+源碼+數據庫+畢業論文+遠程部署】

摘 要 使用舊方法對校園活動資訊進行系統化管理已經不再讓人們信賴了&#xff0c;把現在的網絡信息技術運用在校園活動資訊的管理上面可以解決許多信息管理上面的難題&#xff0c;比如處理數據時間很長&#xff0c;數據存在錯誤不能及時糾正等問題。 這次開發的校園活動資訊網…

關于echarts的性能優化考慮

作為資深前端工程師&#xff0c;在處理 ECharts 性能問題時&#xff0c;核心思路是減少渲染壓力、優化數據處理、避免不必要的計算&#xff0c;尤其在大數據量&#xff08;萬級以上&#xff09;、高頻交互或多圖表場景下&#xff0c;性能優化尤為關鍵。以下是實戰中驗證過的有效…

汽車EDI:Vitesco EDI 項目案例

Vitesco Technologies&#xff08;緯湃科技&#xff09;脫胎于大陸集團的動力總成部門&#xff0c;是一家于2021年上市的全球領先汽車技術供應商。公司專注于電動出行領域&#xff0c;提供電驅動系統、電池管理系統、功率電子及熱管理等關鍵技術解決方案。同時&#xff0c;其業…

譯|Netflix 技術博客:一個利用視覺-語言模型和主動學習高效構建視頻分類器的框架

本篇介紹了Netflix的視頻標注器&#xff08;VA&#xff09;&#xff0c;一個利用視覺-語言模型和主動學習的交互式框架。其技術亮點在于通過人機協作系統&#xff0c;結合零樣本能力和主動學習&#xff0c;引導領域專家高效標注視頻數據&#xff0c;顯著提升了模型樣本效率和平…

前端應用權限設計面面觀

目錄 1. 權限設計:前端為啥要操這份心? 2. 權限模型的“內功心法”:RBAC 和 ABAC RBAC:簡單粗暴的角色分配 ABAC:靈活但燒腦的屬性控制 3. 權限數據的“物流體系”:從后端到前端的旅程 權限數據從哪兒來? 權限數據咋存? 權限數據咋用? 4. 路由守衛:權限的“第…

Javaweb————Apache Tomcat服務器介紹及Windows,Linux,MAC三種系統搭建Apache Tomcat

&#x1f3cd;?&#x1f3cd;?&#x1f3cd;?第一部分&#xff1a;什么是服務器&#xff1f; 服務器是遠程的一個電腦,里面安裝服務器程序監聽對應的端口對外提供服務&#xff0c;可以根據用戶的請求去獲取對應的數據并返回給調用方。 &#x1f3cd;?&#x1f3cd;?&#…

winsock socket通訊為什么UDP服務器無法獲取客戶端IP?

針對VB6 Winsock開發中UDP服務器無法獲取客戶端IP的問題&#xff0c;以下是系統性排查方案&#xff1a; 一、基礎協議特性確認UDP無連接特性 Winsock的UDP協議本身是無連接的&#xff0c;需通過GetPeerName方法主動獲取對端IP&#xff0c;而非自動存儲。數據接收處理 必須在Dat…

大模型時代,Transformer 架構中的核心注意力機制算法詳解與優化實踐

大模型時代&#xff0c;Transformer 架構中的核心注意力機制算法詳解與優化實踐Transformer 注意力機制深度解析與工業級優化實踐一、注意力機制核心原理1.1 基礎注意力公式1.2 多頭注意力&#xff08;Multi-Head&#xff09;1.3 注意力機制可視化二、工業級優化技術2.1 計算效…

自學嵌入式 day40 51單片機

一、嵌入式&#xff1a;以應用為中心&#xff0c;計算機為基礎&#xff0c;軟硬件可剪裁的專用計算機系統二、MCU&#xff1a;Micro Controcler Unit 微控制單元->單片機1、特點&#xff1a;集成化高&#xff0c;集成到一塊芯片外設&#xff08;GPIO、UART、ADC&#xff09;…

Minimizing Coins(Dynamic Programming)

題目描述Consider a money system consisting of n coins. Each coin has a positive integer value. Your task is to produce a sum of money x using the available coins in such a way that the number of coins is minimal. For example, if the coins are {1,5,7} and t…

Kafka——關于Kafka動態配置

引言在Kafka的運維實踐中&#xff0c;參數配置的調整曾是一件令工程師頭疼的事情。傳統模式下&#xff0c;Broker的所有參數都需要在server.properties中靜態定義&#xff0c;任何修改都必須重啟Broker才能生效。對于承載著核心業務的生產集群而言&#xff0c;頻繁重啟不僅意味…

MSQL-聚簇索引與非聚簇索引的比較

聚簇索引詳解InnoDB 的聚簇索引特性表數據本身就是聚簇索引&#xff1a;數據行實際存儲在聚簇索引的葉子節點中"表就是索引&#xff0c;索引就是表"的結構每個InnoDB表有且只有一個聚簇索引聚簇索引的葉子節點存儲的是&#xff1a;真實數據主鍵作為聚簇索引&#xff…

語音識別數據集

目錄 Voice Activity Detection 自己采集&#xff1a; 1. ASR Resources&#xff08;語音識別資源&#xff09; 2. LM Resources&#xff08;語言模型資源&#xff09; 這是一個數據表&#xff1a; 噪聲數據集&#xff1a; Voice Activity Detection 自己采集&#xff1a…

Linux線程同步與互斥(上)

目錄 前言 1.互斥 1.先來見一種現象&#xff08;數據不一致問題&#xff09; 2.如何解決上述問題 3.理解為什么數據會不一致&&認識加鎖的接口 4.理解鎖 5.鎖的封裝 前言 在前面對線程的概念和控制的學習過程中&#xff0c;我們知道了線程是共享地址空間的&#…

Codeforces Global Round 27

ABC 略D將每個數拆成x*2的整數次冪&#xff0c;一個直接的想法是盡量把2的整數次冪給大的數。那么所有乘上2的整數次冪的數構成的序列單調遞減&#xff0c;反證法&#xff0c;如果序列中存在i j 使得a[i]<a[j]&#xff0c;那么我們不如把給a[i]乘的2的冪給a[j]乘。#include …