1

My string is !!(!()). I want to remove double exclamation from the string.

This works but it removes all exclamations

remove_copy(str.begin(), str.end(),ostream_iterator<char>(cout), '!');//gives (())

This does not work

remove_copy(str.begin(), str.end(),ostream_iterator<string>(cout), "!!");

Using the above line throws this error

/usr/include/c++/5/bits/predefined_ops.h:194:17: error: ISO C++ forbids comparison between pointer and integer [-fpermissive] { return *__it == _M_value; }

Pdksock
  • 1,042
  • 2
  • 13
  • 26
  • A reference makes it apparent that there's no overload taking a string specifically. – chris Jul 15 '16 at 05:44
  • @chris ostream_iterator has `template >`. This means I can use string right? – Pdksock Jul 15 '16 at 05:49
  • 1
    @SamidhT string is a list of characters . remove_copy iterates through the list and removes the char. It can work with list of strings as well. – Balu Jul 15 '16 at 05:54
  • @SamidhT, I meant `remove_copy`, not `ostream_iterator`. It doesn't take the same type as what you're iterating over. – chris Jul 15 '16 at 06:03
  • I think you're asking about how to remove a substring from a `std::string`, so refer to https://stackoverflow.com/questions/32435003/how-to-remove-all-substrings-from-a-string – Mine Jul 15 '16 at 06:47

2 Answers2

0

Reading the docs of remove_copy

OutputIterator remove_copy (InputIterator first, InputIterator last,
                          OutputIterator result, const T& val);

The function uses operator== to compare the individual elements to val.

So it uses every character of string and compares it with val. So second case would not work.

I ended up doing it this way

str.erase(str.find("!!"),2);

Also make sure that the string has "!!" otherwise program crashes

if(str.find("!!") != string::npos)
    str.erase(str.find("!!"),2);
Pdksock
  • 1,042
  • 2
  • 13
  • 26
  • Your edited code does the `find` twice, that's a waste of time, you've already found it once! It should be: `auto pos = str.find("!!"); if (pos != string::npos) str.erase(pos, 2);` Also, what if there is more than one occurrence of `"!!"` in the string? What if there is `"!!!"`? This is not a very general solution to the problem. – Jonathan Wakely Jul 15 '16 at 08:04
  • @JonathanWakely if there is "!!!" it really depends on how you want to handle it (2 instances of !! vs 1). Nevertheless I still agree with you, it's not generalized nor efficient. – Pdksock Jul 15 '16 at 10:29
0

Why you cannot use remove_copy(str.begin(), str.end(),ostream_iterator<string>(cout), "!!"); :

https://www.cplusplus.com/reference/algorithm/remove_copy_if/

pred
Unary function that accepts an element in the range as argument, and returns a value convertible to bool. The value returned indicates whether the element is to be removed from the copy (if true, it is not copied). The function shall not modify its argument. This can either be a function pointer or a function object.

jian
  • 4,119
  • 1
  • 17
  • 32