一个打印目录树的例子

输入一个多行的字符串,表示目录树。对其进行解析,并按层次结构打印出目录


/*
* n_number_sum_equal_m.cpp
*
*/

#include<iostream>
#include <map>
#include <string>
#include <vector>
#include <string.h>
#include <algorithm>
using namespace std;

typedef pair<int, string> Token_t;
void token(const string &str, vector<Token_t> &vec) {
	string word;
	string::size_type cur, pre = 0;
	while ((cur = str.find('/', pre)) != string::npos) {
		if (cur > pre)
			vec.push_back(make_pair(vec.size(), str.substr(pre, cur - pre)));
		pre = cur + 1;
	}
	cur = str.size();
	if (cur > pre)
		vec.push_back(make_pair(vec.size(), str.substr(pre, cur - pre)));
}

void put(map<Token_t, vector<Token_t> > & cont, const vector<Token_t> & vec) {
	map<Token_t, vector<Token_t> >::iterator iter;
	Token_t token;
	for (size_t i = 0; i < vec.size(); ++i) {
		iter = cont.find(vec[i]);
		if (iter != cont.end()) {
			token = vec[i];
			continue;
		}
		cont[vec[i]];
		cont[token].push_back(vec[i]);
		token = vec[i];
	}
}

void print(const map<Token_t, vector<Token_t> > & cont, map<Token_t, vector<
	Token_t> >::const_iterator iter) {
	if (iter != cont.end()){
		int n = iter->first.first;
		for (int i = 0; i < n; ++i)
			cout << "    ";
		if (!(iter->first.second.empty()))
			cout << iter->first.second << "\n";

		const vector<Token_t> &vec = iter->second;
		for (size_t i = 0; i < vec.size(); ++i){
			iter = cont.find(vec[i]);
			print(cont, iter);
		}
	}
}

void display(const map<Token_t, vector<Token_t> > & cont) {
	Token_t t;
	if (cont.count(t) > 0) {
		// 调用递归算法打印token
		print(cont, cont.find(t));
	}
}

int main() {
	string dir[5] = { "usr/local/bin", "usr/bin", "bin", "usr/share", "zip" };
	map<Token_t, vector<Token_t> > content;
	vector<Token_t> vec;
	for (int i = 0; i < 5; ++i) {
		// 分解dir
		token(dir[i], vec);
		// 将每个token加入到一个map中,map的键为token的层数和名称,值为每个token
		// 对应的子目录的token
		put(content, vec);
		vec.clear();
	}
	map<Token_t, vector<Token_t> >::iterator iter = content.begin();
	// 排序每个token所对应子目录的所有token
	for (; iter != content.end(); ++iter)
		sort(iter->second.begin(), iter->second.end());
	// 显示
	display(content);
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值