C++中要從string中刪除所有某個特定字符, 可用如下代碼
str.erase(std::remove(str.begin(), str.end(), 'a'), str.end());
其中, remove來自<algorithm>, 它的簽名是
template <class ForwardIterator, class T> ForwardIterator remove (ForwardIterator first, ForwardIterator last, const T& val);
作用: 在容器中, 刪除[first, last)之間的所有值等於val的值.
刪除方法: 將某個等於val的值用下一個不等於val的值覆蓋.
返回值: 一個迭代器 (記作newEnd), 該迭代器指向最后一個未被刪除元素的下一個元素, 即相當於容器新的end.
所以, 運行完remove后, 容器的[first, newEnd)內的元素即為所有未被刪除的元素, [newEnd, end)之間的元素已經沒用了.
這樣, 再運行str.erase(newEnd, str.end())即可清空[newEnd, end)之間的元素.
std::remove_if與remove類似, 只是它接受的第三個參數是個函數.
// remove_if example #include <iostream> // std::cout #include <algorithm> // std::remove_if bool IsOdd (int i) { return ((i%2)==1); } int main () { int myints[] = {1,2,3,4,5,6,7,8,9}; // 1 2 3 4 5 6 7 8 9 // bounds of range: int* pbegin = myints; // ^ int* pend = myints+sizeof(myints)/sizeof(int); // ^ ^ pend = std::remove_if (pbegin, pend, IsOdd); // 2 4 6 8 ? ? ? ? ? // ^ ^ std::cout << "the range contains:"; for (int* p=pbegin; p!=pend; ++p) std::cout << ' ' << *p; std::cout << '\n'; return 0; }
Output:
myvector contains: 10 30 30 10 10 0 0 0
還有個std::remove_copy, 簽名:
template <class InputIterator, class OutputIterator, class T> OutputIterator remove_copy (InputIterator first, InputIterator last, OutputIterator result, const T& val);
它會把[first, last)之間不等於val的元素都向從result開始的容器拷貝.
// remove_copy example #include <iostream> // std::cout #include <algorithm> // std::remove_copy #include <vector> // std::vector int main () { int myints[] = {10,20,30,30,20,10,10,20}; // 10 20 30 30 20 10 10 20 std::vector<int> myvector (8); std::remove_copy (myints,myints+8,myvector.begin(),20); // 10 30 30 10 10 0 0 0 std::cout << "myvector contains:"; for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it) std::cout << ' ' << *it; std::cout << '\n'; return 0; }
Output:
myvector contains: 10 30 30 10 10 0 0 0
