我试图将字符串路径插入到trie数据结构中,但是我无法在child和root之间建立关系。好像我没有插入 元素以适当的方式进入特里。 对于前。 / AB / CD / DE 1.首先,我插入AB(可以正常工作) 2.当我尝试插入CD AB时会被CD覆盖
在创建Trie的过程中,我做错了。我正在尝试实现以下方式
AB
\
CD
/ \
DE EF
我的输入是这样的绝对Unix路径:
/ AB / CD / DE
/ AB / CD / GH
Output of below program
processing path /AB/CD/DE
processing path /AB/CD/FG
AB
CD
Segmentation fault
所以我可以轻松地转换成特里。
#include<algorithm>
#include<iostream>
#include<fstream>
#include<queue>
#include<vector>
#include<boost/filesystem.hpp>
#include<boost/tokenizer.hpp>
#include <boost/algorithm/string.hpp>
#include<utility>
#include "Command.h"
namespace fs = boost::filesystem;
struct Dirinfo {
std::vector<std::pair<std::string,Dirinfo*>>list;
bool leaf_node;
};
class Dirmapping {
private:
Dirinfo *root = nullptr;
std::vector<std::string> dirs;
public:
Dirmapping() = default;
Dirmapping(const std::vector<std::string> &dir_name);
Dirinfo* getnode();
Dirinfo* getchild(Dirinfo *tmp, const std::string &dir_name);
void createmap();
void display(Dirinfo *root);
};
Dirmapping::Dirmapping(const std::vector<std::string> &dirs): dirs(dirs) {
root = getnode();
}
Dirinfo* Dirmapping::getnode() {
Dirinfo *node = new Dirinfo;
node->leaf_node = false;
return node;
}
Dirinfo* Dirmapping::getchild(Dirinfo *tmp, const std::string &dir_name){
for(auto it = tmp->list.begin(); it != tmp->list.end(); ++it){
if(it->first == dir_name){
it->second->leaf_node = false;
return it->second;
}
}
tmp->list.push_back(make_pair(dir_name, getnode()));
tmp->leaf_node = true;
return tmp;
}
void Dirmapping::createmap() {
Dirinfo *temp = root;
for(auto it = this->dirs.begin(); it != dirs.end(); ++it) {
std::vector<std::string> split_string = Command::split_path(*it);
std::cout<<"processing path "<<*it<<std::endl;
for (auto split_it = split_string.begin(); split_it != split_string.end(); ++split_it){
temp = getchild(temp, *split_it);
}
}
display(root);
}
void Dirmapping::display(Dirinfo *root)
{
if (!root->leaf_node)
std::cout<<root->list[0].first<<std::endl;
for(auto it = root->list.begin(); it != root->list.end(); ++it){
if (it->second)
display(it->second);
}
}
int main() {
std::vector<std::string> dir_names;
dir_names.push_back("/AB/CD/DE");
dir_names.push_back("/AB/CD/FG");
Dirmapping dirmap(dir_names);
dirmap.createmap();
return 0;
}
Command.h
command.h,它使用“ /”分割字符串
namespace Command {
inline std::vector<std::string> split_path(const std::string &f_path) {
std::vector<std::string> token_string;
boost::char_separator<char> split("/", "\n");
tokenizer tok(f_path, split);
for(tokenizer :: iterator it = tok.begin(); it != tok.end(); ++it) {
token_string.push_back(*it);
}
return token_string;
}
}