我試圖從字符串中刪除連續的重複字符,如"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