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

Any way to get split_regex to accept a const string as input?

以下 code 如果我尝试将字符串输入设为 const,编译将崩溃并出现深度模板错误堆栈,但我不明白为什么它应该是可变的。

考虑到算法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; 一起工作?

根据评论,如果正在搜索的 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;
    }
}