好!我明白了!💥
你希望我在你的基礎上,繼續優化 insertPathWithIds,讓它:
? 支持每一級節點的 idPart 是字符串(而不是int)。
? 結構更清晰,更快拼接。
? 完全符合C++98標準。
那我給你一版「超清爽」的改進版:
?
🌟 新版 STDTMDirTree(C++98標準)
#include
#include
#include
#include
#include
namespace STDTM {
class STDTMDirTree {
private:
struct Node {
std::map<std::string, Node*> children;
std::string idPart; // 當前節點對應的ID部分
};
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'; // 補0}result[TOTAL_DIGITS] = '\0'; // 結束符
}
public:
STDTMDirTree() {
root = new Node();
}
~STDTMDirTree() {clear(root);
}// 插入路徑和每一級的idPart
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];}
}// 根據路徑得到完整ID
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);
}
};
} // namespace STDTM
?
🧠 這版的核心變化:
? idPart 從 int ? std::string,一層一段。
? 拼接ID時,直接用 char result[6] 一次性拼,不用 ostringstream,超快!
? 補齊5位數字,多的截掉,少的補0,嚴格控制位數。
? insert和get都干干凈凈,沒有花哨操作。
?
📦 使用示例:
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
?
要不要我順便也幫你寫一個反向接口,比如給定ID快速找到路徑?
如果要,告訴我:「繼續寫 getPathFromId」!🚀