映射關系5

明白!🚀
你要我 繼續擴展,在這套 C++98 代碼里加一個功能:

根據完整的5位ID,反查出對應的路徑。

OK,我直接接著上面那版來,給你補充 getPathFromId 方法,并且保持整體風格統一,簡潔、高效!

?

? 完整加上 getPathFromId 的 STDTMDirTree

#include
#include
#include
#include
#include

namespace STDTM {

class STDTMDirTree {
private:
struct Node {
std::map<std::string, Node*> children;
std::string idPart;
};

Node* root;
static const size_t TOTAL_DIGITS = 5;void clear(Node* node) {std::map<std::string, Node*>::iterator it;for (it = node->children.begin(); it != node->children.end(); ++it) {clear(it->second);}delete node;
}std::vector<std::string> splitPath(const std::string& path) const {std::vector<std::string> parts;std::string part;for (size_t i = 0; i < path.length(); ++i) {if (path[i] == '/') {if (!part.empty()) {parts.push_back(part);part.clear();}} else {part += path[i];}}if (!part.empty()) {parts.push_back(part);}return parts;
}void buildIdString(const std::vector<std::string>& idParts, char result[TOTAL_DIGITS + 1]) const {size_t pos = 0;for (size_t i = 0; i < idParts.size(); ++i) {const std::string& part = idParts[i];for (size_t j = 0; j < part.size() && pos < TOTAL_DIGITS; ++j) {result[pos++] = part[j];}}while (pos < TOTAL_DIGITS) {result[pos++] = '0';}result[TOTAL_DIGITS] = '\0';
}bool findPathRecursive(Node* node, const char* id, size_t pos, std::string currentPath, std::string& foundPath) const {if (pos >= TOTAL_DIGITS) {foundPath = currentPath;return true;}std::map<std::string, Node*>::const_iterator it;for (it = node->children.begin(); it != node->children.end(); ++it) {Node* child = it->second;const std::string& part = child->idPart;if (pos + part.size() > TOTAL_DIGITS) {continue; // 超出,總位數不允許}bool match = true;for (size_t i = 0; i < part.size(); ++i) {if (id[pos + i] != part[i]) {match = false;break;}}if (match) {std::string newPath = currentPath + "/" + it->first;if (findPathRecursive(child, id, pos + part.size(), newPath, foundPath)) {return true;}}}return false;
}

public:
STDTMDirTree() {
root = new Node();
}

~STDTMDirTree() {clear(root);
}void insertPathWithIds(const std::string& path, const std::vector<std::string>& idParts) {Node* current = root;std::vector<std::string> parts = splitPath(path);if (parts.size() != idParts.size()) {throw std::string("Error: Path and idParts size mismatch");}for (size_t i = 0; i < parts.size(); ++i) {const std::string& name = parts[i];if (current->children.count(name) == 0) {Node* newNode = new Node();newNode->idPart = idParts[i];current->children[name] = newNode;}current = current->children[name];}
}std::string getIdFromPath(const std::string& path) const {Node* current = root;std::vector<std::string> parts = splitPath(path);std::vector<std::string> idParts;for (size_t i = 0; i < parts.size(); ++i) {const std::string& name = parts[i];if (current->children.count(name) == 0) {return "[Path not found]";}current = current->children.find(name)->second;idParts.push_back(current->idPart);}char result[TOTAL_DIGITS + 1];buildIdString(idParts, result);return std::string(result);
}std::string getPathFromId(const std::string& id) const {if (id.size() != TOTAL_DIGITS) {return "[Invalid ID]";}std::string foundPath;if (findPathRecursive(root, id.c_str(), 0, "", foundPath)) {return foundPath;} else {return "[Path not found]";}
}

};

} // namespace STDTM

?

🧠 說明
? findPathRecursive :從樹根出發,按ID去匹配,一層層往下走。
? 每次檢查節點的idPart,必須能對應上 id 數組的相應位置。
? 如果能一路匹配到5位數字填滿,就找到路徑了!

?

📦 使用示例

STDTM::STDTMDirTree tree;
tree.insertPathWithIds(“/robot/arm1”, std::vectorstd::string{“1”, “234”});
tree.insertPathWithIds(“/station/slot3”, std::vectorstd::string{“23”, “456”});

std::cout << tree.getIdFromPath(“/robot/arm1”) << std::endl; // 12340
std::cout << tree.getIdFromPath(“/station/slot3”) << std::endl; // 23456

std::cout << tree.getPathFromId(“12340”) << std::endl; // /robot/arm1
std::cout << tree.getPathFromId(“23456”) << std::endl; // /station/slot3

?

要不要我順便再教你一招,怎么加速查詢?比如維護一個id到路徑的哈希表,瞬間查出路徑,速度還能提一檔。要的話告訴我:「繼續加速版本!」🚀
要不要?😎

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/diannao/80916.shtml
繁體地址,請注明出處:http://hk.pswp.cn/diannao/80916.shtml
英文地址,請注明出處:http://en.pswp.cn/diannao/80916.shtml

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

相關文章

編譯原理:由淺入深從語法樹到文法類型

文法與語言基礎&#xff1a;從語法樹到文法類型 文法&#xff08;Grammar&#xff09;和語言&#xff08;Language&#xff09;是計算機科學和語言學中解析和理解語言結構的核心概念。無論是編程語言的編譯器設計&#xff0c;還是自然語言處理&#xff08;NLP&#xff09;中的…

第十三步:vue

Vue 1、上手 1、安裝 使用命令&#xff1a;npm create vuelatestvue文件后綴為.vueconst app createApp(App)&#xff1a;初始化根組件app.mount("#app")&#xff1a;掛載根組件到頁面 2、文件 script標簽&#xff1a;編寫jstemplate標簽&#xff1a;編寫htmls…

Pytest-mark使用詳解(跳過、標記、參數 化)

1.前言 在工作中我們經常使用pytest.mark.XXXX進行裝飾器修飾&#xff0c;后面的XXX的不同&#xff0c;在pytest中有不同的作 用&#xff0c;其整體使用相對復雜&#xff0c;我們單獨將其抽取出來做詳細的講解。 2.pytest.mark.skip()/skipif()跳過用例 import pytest #無條…

基于 Spring Boot 的井字棋游戲開發與實現

目錄 引言 項目概述 項目搭建 1. 環境準備 2. 創建 Spring Boot 項目 3. 項目結構 代碼實現 1. DemoApplication.java 2. TicTacToeController.java 3. pom.xml 電腦落子策略 - Minimax 算法 findBestMove 方法 minimax 方法 運行游戲 總結 引言 在軟件開發領域&…

【算法筆記】貪心算法

一、什么是貪心算法&#xff1f; 貪心算法是一種在每一步選擇中都采取當前看起來最優&#xff08;最“貪心”&#xff09;的策略&#xff0c;從而希望得到全局最優解的算法設計思想。 核心思想&#xff1a;每一步都做出局部最優選擇&#xff0c;不回退。適用場景&#xff1a;…

現代c++獲取linux所有的網絡接口名稱

現代c獲取linux所有的網絡接口名稱 前言一、在linux中查看網絡接口名稱二、使用c代碼獲取三、驗證四、完整代碼如下五、總結 前言 本文介紹一種使用c獲取本地所有網絡接口名稱的方法。 一、在linux中查看網絡接口名稱 在linux系統中可以使用ifconfig -a命令列舉出本機所有網絡…

打印及判斷回文數組、打印N階數組、蛇形矩陣

打印回文數組 1 1 1 1 1 1 2 2 2 1 1 2 3 2 1 1 2 2 2 1 1 1 1 1 1方法1&#xff1a; 對角線對稱 左上和右下是對稱的。 所以先考慮左上打印&#xff0c; m i n ( i 1 , j 1 ) \text min(i1,j1) min(i1,j1)&#xff0c;打印出來&#xff1a; 1 1 1 1 1 2 2 2 1 2 3 3 1 2 …

詳解UnityWebRequest類

什么是UnityWebRequest類 UnityWebRequest 是 Unity 引擎中用于處理網絡請求的一個強大類&#xff0c;它可以讓你在 Unity 項目里方便地與網絡資源進行交互&#xff0c;像發送 HTTP 請求、下載文件等操作都能實現。下面會詳細介紹 UnityWebRequest 的相關內容。 UnityWebRequ…

UE5 在旋轉A的基礎上執行旋轉B

用徑向slider實現模型旋轉時&#xff0c;得到的結果與ue編輯器里面的結果有很大出入。 問題應該是 兩個FRotator&#xff08;0&#xff0c;10&#xff0c;0&#xff09;和&#xff08;10&#xff0c;20&#xff0c;30&#xff09;&#xff0c; 兩個FRotator的加法結果為&…

4.2 Prompt工程與任務建模:高效提示詞設計與任務拆解方法

提示詞工程&#xff08;Prompt Engineering&#xff09;和任務建模&#xff08;Task Modeling&#xff09;已成為構建高效智能代理&#xff08;Agent&#xff09;系統的核心技術。提示詞工程通過精心設計的自然語言提示詞&#xff08;Prompts&#xff09;&#xff0c;引導大型語…

MySQL 索引的最左前綴匹配原則是什么?

MySQL 索引的最左前綴匹配原則詳解 最左前綴匹配原則&#xff08;Leftmost Prefix Principle&#xff09;是 MySQL 復合索引&#xff08;聯合索引&#xff09;查詢優化中的核心規則&#xff0c;理解這一原則對于高效使用索引至關重要。 核心概念 定義&#xff1a;當查詢條件…

SQL命令

一、控制臺中查詢命令 默認端口號&#xff1a;3306 查看服務器版本: mysql –version 啟動MySQL服務&#xff1a;net start mysql 登錄數據庫&#xff1a;mysql -u root -p 查看當前系統下的數據庫&#xff1a;show databases&#xff1b; 創建數據庫&#xff1a;create…

新增 29 個專業,科技成為關鍵賽道!

近日&#xff0c;教育部正式發布《普通高等學校本科專業目錄&#xff08;2025年&#xff09;》&#xff0c;新增 29 個本科專業&#xff0c;包括區域國別學、碳中和科學與工程、海洋科學與技術、健康與醫療保障、智能分子工程、醫療器械與裝備工程、時空信息工程、國際郵輪管理…

零基礎上手Python數據分析 (23):NumPy 數值計算基礎 - 數據分析的加速“引擎”

寫在前面 —— 超越原生 Python 列表,解鎖高性能數值計算,深入理解 Pandas 的底層依賴 在前面一系列關于 Pandas 的學習中,我們已經領略了其在數據處理和分析方面的強大威力。我們學會了使用 DataFrame 和 Series 來高效地操作表格數據。但是,你是否好奇,Pandas 為何能夠…

Android 13.0 MTK Camera2 設置默認拍照尺寸功能實現

Android 13.0 MTK Camera2 設置默認拍照尺寸功能實現 文章目錄 需求&#xff1a;參考資料架構圖了解Camera相關專欄零散知識了解部分相機源碼參考&#xff0c;學習API使用&#xff0c;梳理流程&#xff0c;偏應用層Camera2 系統相關 修改文件-修改方案修改文件&#xff1a;修改…

HarmonyOS 框架基礎知識

參考文檔&#xff1a;HarmonyOS開發者文檔 第三方庫&#xff1a;OpenHarmony三方庫中心倉 基礎特性 Entry&#xff1a;關鍵裝飾器 Components&#xff1a;組件 特性EntryComponent??作用范圍僅用于頁面入口可定義任意可復用組件??數量限制??每個頁面有且僅有一個無數量…

前端分頁與瀑布流最佳實踐筆記 - React Antd 版

前端分頁與瀑布流最佳實踐筆記 - React Antd 版 1. 分頁與瀑布流對比 分頁&#xff08;Pagination&#xff09;瀑布流&#xff08;Infinite Scroll&#xff09;展示方式按頁分批加載&#xff0c;有明確頁碼控件滾動到底部時自動加載更多內容&#xff0c;無明顯分頁用戶控制用…

Linux網絡編程:TCP多進程/多線程并發服務器詳解

Linux網絡編程&#xff1a;TCP多進程/多線程并發服務器詳解 TCP并發服務器概述 在Linux網絡編程中&#xff0c;TCP服務器主要有三種并發模型&#xff1a; 多進程模型&#xff1a;為每個客戶端連接創建新進程多線程模型&#xff1a;為每個客戶端連接創建新線程I/O多路復用&am…

詳解springcloudalibaba采用prometheus+grafana實現服務監控

文章目錄 1.官網下載安裝 prometheus和grafana1.promethus2.grafana 2. 搭建springcloudalibaba集成prometheus、grafana1. 引入依賴,springboot3.2之后引入如下2. 在yml文件配置監控端點暴露配置3. 在當前啟動的應用代碼中添加&#xff0c;在prometheus顯示的時候附加當前應用…

數據分析1

一、常用數據處理模塊Numpy Numpy常用于高性能計算&#xff0c;在機器學習常常作為傳遞數據的容器。提供了兩種基本對象&#xff1a;ndarray、ufunc。 ndarray具有矢量算術運算和復雜廣播能力的快速且節省空間的多維數組。 ufunc提供了對數組快速運算的標準數學函數。 ndar…