Search code examples
c++boosttext-parsing

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


Following code compilation implodes with deep template error stack if I try to make string input const, but I do not understand why it should be mutable.

From thinking about algorithm const should be fine, also I checked that the argument is not modified after function call.

#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;
    }
}

Any way to make this code work with const std::string str;?


Solution

  • As per the comment, if the std::string being searched is const then the iterator type used in the results must be the associated const_iterator type for the container being searched. Hence if the string being searched is...

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

    Then the results container should be...

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

    So the complete example becomes...

    #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;
        }
    }