如果我尝试将字符串输入设置为常量,则遵循 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;
一起使用?
答案 0 :(得分:3)
根据评论,如果正在搜索的 std::string
是 const
,那么结果中使用的迭代器类型必须是与正在搜索的容器相关联的 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;
}
}