(原創) 如何使用remove() algorithm? (C/C++) (STL)
remove()將移除container中所有的指定元素,但基於不改變Contaier size的原則,remove()只是將要移除的元素搬到contaier後面,若要真正移除,還要搭配contaier.erase()。
1
/*
2
(C) OOMusou 2006 http://oomusou.cnblogs.com
3
4
Filename : GenericAlgo_remove.cpp
5
Compiler : Visual C++ 8.0 / ISO C++
6
Description : Demo how to use remove() algorithm
7
Release : 11/15/2006 1.0
8
12/14/2006 2.0
9
05/16/2007 3.0
10
*/
11
#include <iostream>
12
#include <string>
13
#include <vector>
14
#include <algorithm>
15
#include <sstream>
16
17
using namespace std;
18
19
int main() {
20
// You can use push_back to insert vector.
21
// I use string -> stringstream -> vector to shorten code lines.
22
string s = "To be or not to be is a question";
23
istringstream ss(s);
24
vector<string> svec;
25
copy(istream_iterator<string>(ss), istream_iterator<string>(), back_inserter(svec));
26
27
// remove all "be" in the vector
28
svec.erase(remove(svec.begin(),svec.end(),"be"), svec.end());
29
30
copy(svec.begin(), svec.end(), ostream_iterator<string>(cout, "\n"));
31
}
/* 2
(C) OOMusou 2006 http://oomusou.cnblogs.com3

4
Filename : GenericAlgo_remove.cpp5
Compiler : Visual C++ 8.0 / ISO C++6
Description : Demo how to use remove() algorithm7
Release : 11/15/2006 1.08
12/14/2006 2.09
05/16/2007 3.010
*/11
#include <iostream>12
#include <string>13
#include <vector>14
#include <algorithm>15
#include <sstream>16

17
using namespace std;18

19
int main() {20
// You can use push_back to insert vector.21
// I use string -> stringstream -> vector to shorten code lines.22
string s = "To be or not to be is a question";23
istringstream ss(s);24
vector<string> svec;25
copy(istream_iterator<string>(ss), istream_iterator<string>(), back_inserter(svec));26

27
// remove all "be" in the vector28
svec.erase(remove(svec.begin(),svec.end(),"be"), svec.end());29

30
copy(svec.begin(), svec.end(), ostream_iterator<string>(cout, "\n"));31
}
執行結果
To
or
not
to
is
a
question
22行到25行
string s = "To be or not to be is a question";
istringstream ss(s);
vector<string> svec;
copy(istream_iterator<string>(ss), istream_iterator<string>(), back_inserter(svec));
當然可以使用vector的push_back(),但我為了減少行數,使用了string -> stringstream -> vector的小技巧,將可大幅降低程式碼行數。
28行
svec.erase(remove(svec.begin(),svec.end(),"be"), svec.end());
為remove()的使用方式,程式中將移除所有"be"字串,但要搭配erase()後,才能真正完整remove。


浙公网安备 33010602011771号