php 做网站xml地图,回龙观手机网站开发服务,吉首企业自助建站,网页版微信暂时无法登陆好#xff01;我明白了#xff01;#x1f4a5; 你希望我在你的基础上#xff0c;继续优化 insertPathWithIds#xff0c;让它#xff1a; • 支持每一级节点的 idPart 是字符串#xff08;而不是int#xff09;。 • 结构更清晰#xff0c;更快拼接。 • 完全符合C98…好我明白了 你希望我在你的基础上继续优化 insertPathWithIds让它 • 支持每一级节点的 idPart 是字符串而不是int。 • 结构更清晰更快拼接。 • 完全符合C98标准。
那我给你一版「超清爽」的改进版
⸻ 新版 STDTMDirTreeC98标准
#include #include #include #include #include
namespace STDTM {
class STDTMDirTree { private: struct Node { std::mapstd::string, Node* children; std::string idPart; // 当前节点对应的ID部分 };
Node* root;
static const size_t TOTAL_DIGITS 5;void clear(Node* node) {std::mapstd::string, Node*::iterator it;for (it node-children.begin(); it ! node-children.end(); it) {clear(it-second);}delete node;
}std::vectorstd::string splitPath(const std::string path) const {std::vectorstd::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::vectorstd::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::vectorstd::string idParts) {Node* current root;std::vectorstd::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::vectorstd::string parts splitPath(path);std::vectorstd::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」