Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use boost::is_any_of with boost::replace_all_copy

Tags:

c++

boost

I am trying to make a simple piece of code work with boost::is_any_of and boost::replace_all_copy. The snippet is below:

std::string someString = "abc.def-ghi";
std::string toReplace = ".-";
std::string processedString = boost::replace_all_copy(someString, boost::is_any_of(toReplace), " ");

However, I get a compiler error that is too long to paste here. Could someone that has experience with these 2 functions please point out my error?

like image 694
czchlong Avatar asked Dec 26 '22 09:12

czchlong


1 Answers

I don't think you can't. The three parameter version of boost::replace_all_copy takes the input string, a substitute string and the string to search for. What boost::is_any_of returns is a predicate functor.

What you probably want is boost::replace_if:

#include <boost/algorithm/string.hpp>            // for is_any_of
#include <boost/range/algorithm/replace_if.hpp>  // for replace_if
#include <string>
#include <iostream>

std::string someString = "abc.def-ghi";
std::string toReplace = ".-";
std::string processedString =
   boost::replace_if(someString, boost::is_any_of(toReplace), ' ');

int main()
{
    std::cout << processedString;
}

This modifies the original, so if you need to keep it, you can use boost::replace_copy_if:

#include <boost/algorithm/string.hpp>
#include <boost/range/algorithm/replace_copy_if.hpp>
#include <string>
#include <iostream>
#include <iterator>    // for back_inserter

std::string someString = "abc.def-ghi";
std::string toReplace = ".-";

int main()
{
    std::string processedString;
    boost::replace_copy_if(someString,
        std::back_inserter(processedString), boost::is_any_of(toReplace), ' ');
    std::cout << processedString;
}

Hope that helps.

like image 150
jrok Avatar answered Dec 29 '22 04:12

jrok