【问题标题】:Any way to get split_regex to accept a const string as input?有什么方法可以让 split_regex 接受 const 字符串作为输入?
【发布时间】:2021-02-18 16:05:47
【问题描述】:

如果我尝试将字符串输入设为 const,则在 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;一起工作?

【问题讨论】:

  • 你所说的“深度模板错误堆栈”只是一个警告。代码编译,如果你向下滚动,你可以在你的链接中看到它的输出
  • 如果您有const std::string str,那么我认为您需要将results 声明为std::vector&lt;boost::iterator_range&lt;std::string::const_iterator&gt;&gt;(注意const_iterator 而不是iterator)。
  • @largest_prime_is_463035818 就像我说的看到你需要尝试使 str const 的错误
  • @G.M.是的,这解决了它。 :) 也许你想让它成为一个答案
  • 最好发布有问题的代码而不是正常的代码

标签: c++ boost text-parsing


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-08
    • 2017-05-05
    • 1970-01-01
    • 1970-01-01
    • 2012-09-11
    • 1970-01-01
    相关资源
    最近更新 更多