在 cpp 中的无序地图上进行正则表达式模式匹配搜索

Regex pattern match search over an un-ordered map in cpp

我有一个unordered_map,它的键和值都是字符串类型。

键是正则表达式。

地图中的元素数量约为 2,50,000。

我必须找到其键(正则表达式)returns 与请求中收到的字符串完全匹配的元素。

当我按每个元素遍历地图时,在最坏的情况下大约需要 10 秒。

我的示例代码:

string string_to_match = "Find my Regex";
for (MyMap::const_iterator it = myMap.begin();
        it != myMap.end(); ++it) {
    //cout << it->first << "\n";
    if (regex_match( string_to_match ,
            regex(it->first,std::regex::ECMAScript | std::regex::icase))) {
        cout << ", " << it->second << "\n ";
        break;
    }
    ++it;
}

有什么办法可以减少所花的时间...

std::regex 对象的构建需要很多时间,因为正则表达式输入字符串是在构建期间编译的。因此,请提前构建 std::regex 个对象并将它们保存在您选择的容器中。

在预编译的 std::regex 对象上调用 std::regex_match 非常有效。

考虑在构造 std::regex 对象时也传递 std::regex::optimize 标志。这将意味着构建速度更慢,但匹配性能更快。