【发布时间】:2011-09-22 16:13:21
【问题描述】:
我有一个模式匹配例程,它根据用于请求命令的 URL 从 std::map 中查找值。 URL 映射表中的值如下:
// Assume this->commands_ is defined elsewhere as std::map<std::string, int>
// Providing a number of URL examples to give an idea of the structure of
// the URLs
this->commands_["/session"] = 1;
this->commands_["/session/:sessionid/url"] = 2;
this->commands_["/session/:sessionid/back"] = 3;
this->commands_["/session/:sessionid/forward"] = 4;
this->commands_["/session/:sessionid/element"] = 5;
this->commands_["/session/:sessionid/element/:id/text"] = 6;
this->commands_["/session/:sessionid/element/:id/value"] = 7;
每个 URL 模式中的标记(由前面的 ':' 指定)在对查找例程的调用中替换为实际值(例如,"/session/1234-8a0f/element/5bed-6789/text"),但我需要保留命名参数。上述示例中的命名标记列表并不详尽,在上面列出的位置中可能还有其他命名标记。请注意,令牌值是十六进制编码的数字。
目前,我正在遍历映射的键,用正则表达式值替换替换标记,并使用 std::tr1 正则表达式类对请求的值执行正则表达式匹配,将匹配的标记名称和值捕获到向量。该代码在功能上与此等价(为清楚起见,代码比通常编写的更冗长):
// Assume "using namespace std;" has been declared,
// and appropriate headers #included.
int Server::LookupCommand(const string& uri,
vector<string>* names,
vector<string>* values) {
int value = 0;
// Iterate through the keys of the map
map<string, int>::const_iterator it = this->commands_.begin();
for (; it != this->commands_.end(); ++it) {
string url_candidate = it->first;
// Substitute template parameter names with regex match strings
size_t param_start_pos = url_candidate.find_first_of(":");
while (param_start_pos != string::npos) {
size_t param_len = string::npos;
size_t param_end_pos = url_candidate.find_first_of("/",
param_start_pos);
if (param_end_pos != string::npos) {
param_len = param_end_pos - param_start_pos;
}
// Skip the leading colon
string param_name = url_candidate.substr(param_start_pos + 1,
param_len - 1);
names->push_back(param_name);
url_candidate.replace(param_start_pos,
param_len,
"([0-9a-fA-F-]+)");
param_start_pos = url_candidate.find_first_of(":");
}
tr1::regex matcher("^" + url_candidate + "$");
tr1::match_results<string::const_iterator> matches;
if (tr1::regex_search(uri, matches, matcher)) {
size_t param_count = names->size();
for (unsigned int i = 0; i < param_count; i++) {
// Need i + 1 to get token match; matches[0] is full string.
string param_value = matches[i + 1].str();
values->push_back(param_value);
}
found_value = it->second;
break;
}
}
return value;
}
请注意,我没有使用 Boost 库,也不允许我在这个项目中使用它们。
我觉得这段代码效率非常低,因为我每次都在遍历地图的键,但是我无法看到众所周知的森林,而且我遇到了困难有替代品。虽然描述听起来很荒谬,但我实际上试图构建的是基于键的正则表达式匹配而不是精确匹配的映射查找。我怎样才能使它更有效率?我在设计这个函数时忽略了哪些模式?
【问题讨论】:
-
有趣的问题。但是,从一开始就注意到
std::map在这里根本不是正确的数据结构。它基于键的相对顺序关系提供从精确键到值的映射。你想要一些完全不同的东西,即基于模式匹配关系的键到值的映射。 -
同意地图不是正确的数据结构。我在这里使用它作为 vector
的功能等价物,我将在其中迭代矢量。当这个函数开始它的生命时,地图是正确的结构,但是在需求改变之后,我没有回去更正代码以使用不同的数据结构。最终,这就是问题所在:正确的数据结构是什么?
标签: c++ regex pattern-matching tr1