好!我明白了!💥
你希望我在你的基础上,继续优化 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」!🚀