STL中的unique只能把重復的元素全部放到容器末端,並不能真正把重復元素刪除. 這裡使用unique 和 erase 則可達到徹底刪除效果
示例代碼如下:
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
using namespace std;
void print(string temp)
{
cout<<temp<<endl;
}
int main()
{
vector<string> test;
vector<string>::iterator pos;
string temp;
for (int i=0; i<6;++i)
{
cin>>temp;
test.push_back(temp);
}
cout<<"請輸入";
cin>>temp;
pos=remove(test.begin(),test.end(),temp);//僅僅把temp值賦空並且放到最後一位 沒有徹底刪除
// remove返回最後一個未被移除元素的下一位置
test.erase(pos,test.end()); //刪除pos到test.end()的所有元素
for_each(test.begin(),test.end(),print);
//若然test是list<string> 則直接 test.remove(temp)即可完成徹底刪除
}