3

I found this method on the internet:

//the call to the method: 
cout << convert_binary_to_FANN_array("1001");

//the method in question: 
string convert_binary_to_FANN_array(string binary_string)
{
string result = binary_string;

replace(result.begin(), result.end(), "a", "b ");
replace(result.begin(), result.end(), "d", "c ");
return result;
}

But this gives

main.cpp:30: error: no matching function for call to ‘replace(__gnu_cxx::__normal_iterator<char*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, __gnu_cxx::__normal_iterator<char*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, const char [2], const char [3])’
NullVoxPopuli
  • 61,906
  • 73
  • 206
  • 352

3 Answers3

5

You need characters, not strings, as the third and fourth arguments to replace. Of course that won't do if you really want to replace 'a' with "b ".

So, e.g.,

string convert_binary_to_FANN_array(string binary_string)
{
    string result = binary_string;

    replace(result.begin(), result.end(), 'a', 'b');
    replace(result.begin(), result.end(), 'd', 'c');
    return result;
}

will turn as into b and ds into cs (though why you'd be doing that to a string containing only 0s and 1s, I can't imagine). It won't, however, insert any extra spaces.

If you do need the extra spaces, see (1) the reference provided by Timo Geusch and (2) this: Replace part of a string with another string.

Community
  • 1
  • 1
Gareth McCaughan
  • 19,888
  • 1
  • 41
  • 62
1

Have a look at the documentation for std::string's family of replace functions:

http://www.cplusplus.com/reference/string/string/replace/

You'll see that there is none that allows you to specify a string and a replacement string, they mostly work with offsets/iterators and the replacement.

The boost libraries have a whole slew of replacement algorithms that might be much better suited:

http://www.boost.org/doc/libs/1_46_1/doc/html/string_algo/usage.html#id2728305

Timo Geusch
  • 24,095
  • 5
  • 52
  • 70
0

Another approach if you want to localize the replace's is using a functor...

Example:

#include <string>
#include <algorithm>

struct replaceChar
{
   void operator()(char& c) { if(c == 'a') c = 'b'; }
};

std::string str = "Ababba";

std::for_each(str.begin(), str.end(), replaceChar() );
Abhay
  • 7,092
  • 3
  • 36
  • 50