有什么方法可以让 split_regex 接受一个 const 字符串作为输入?

时间:2021-02-18 16:05:47

标签: c++ boost text-parsing

如果我尝试将字符串输入设置为常量,则遵循 code 编译会因深模板错误堆栈而内爆,但我不明白为什么它应该是可变的。

从考虑算法 const 应该没问题,我还检查了函数调用后参数没有被修改。

#include <string>
#include <iostream>
#include <boost/algorithm/string_regex.hpp>

int main()
{
    std::string str("helloABboostABworld");
    static const boost::regex re("AB");
    std::vector<boost::iterator_range<std::string::iterator> > results;
    boost::split_regex(results, boost::make_iterator_range(str.begin(),
    str.end()), re);
    for (const auto& range: results){
        std::cout << std::string(range.begin(), range.end()) << std::endl;
    }
}

有什么方法可以使此代码与 const std::string str; 一起使用?

1 个答案:

答案 0 :(得分:3)

根据评论,如果正在搜索的 std::stringconst,那么结果中使用的迭代器类型必须是与正在搜索的容器相关联的 const_iterator 类型。因此,如果正在搜索的字符串是...

const std::string str("helloABboostABworld");

那么结果容器应该是...

std::vector<boost::iterator_range<std::string::const_iterator>> results;

所以完整的例子变成...

#include <string>
#include <iostream>
#include <boost/algorithm/string_regex.hpp>

int main()
{
    const std::string str("helloABboostABworld");
    static const boost::regex re("AB");
    std::vector<boost::iterator_range<std::string::const_iterator>> results;
    boost::split_regex(results, boost::make_iterator_range(str.begin(),
    str.end()), re);
    for (const auto& range: results){
        std::cout << std::string(range.begin(), range.end()) << std::endl;
    }
}
相关问题