我想读取文件中正则表达式的出现次数。好吧,我数了一下,但是算法的效率还有很多不足。
unsigned int FileAnalizer::regularCounter(std::string countingReg) {
std::ifstream file(inputFilePath_, std::ios::in);
if (!file) throw std::runtime_error("can't open file " + inputFilePath_);
unsigned int counter(0);
std::string line;
std::regex const expression(countingReg);
while (std::getline(file, line)) {
std::ptrdiff_t const match_count(std::distance(
std::sregex_iterator(line.begin(), line.end(), expression),
std::sregex_iterator()));
counter += match_count;
}
return counter;
}
我认为事实是该算法保持匹配并在分配上花费资源,但是我根本不需要结果行,我可以以某种方式避免这种开销吗?