我试图从字符串中删除连续的重复字符,如"helloworld"
,并删除所有出现的重复字符。在这种情况下,它是'l'
,所以新字符串应该是"heoword"
。我已经写了这样的代码:为什么我需要抛出算法remove()的参数?
#include <algorithm>
#include <string>
#include <iostream>
using namespace std;
int main() {
string s = "helloworld";
for (int i = 0; i < s.length() - 1; i++) {
if (s[i] == s[i+1]) {
s.erase(remove(s.begin(), s.end(), s[i]), s.end()); // PROBLEM
cout << s << endl; // printing `heowrld`, instead of `heoword`
}
}
return 0;
}
上面的代码不工作,除非我投s[i]
喜欢(char)s[i]
。我查找了运算符[]
作为字符串,它将位置处的字符返回给引用。 remove
方法也接受const T& val
作为要替换字符的参数。由于它们都属于同一类型,为什么我不能将s[i]
作为remove
方法的参数?
p.s.这不是家庭作业问题。通过在remove
中投下s[i]
,我可以得到正确的输出,但我想知道为什么我需要投出s[i]
。
什么是确切的编译器错误? – NathanOliver
这可能是家庭作业,因此教官fiat禁止,但[看看'std :: unique'](http://en.cppreference.com/w/cpp/algorithm/unique) – user4581301
@NathanOliver我是没有得到任何错误,但输出是'heowrld'而不是'heoword'。 – pseudo