std::unique

功能:对有序的容器重新排列,将第一次出现的元素从前往后排,其他重复出现的元素依次排在后面

返回值:返回迭代器,迭代器指向的是重复元素的首地址


看不懂表达的看看下面这个简图:

有序的容器:

1123344456

unique处理过的容器:

uniqueuniqueuniqueuniqueuniqueunique迭代器指向的地址   
1234561344


代码如下:

#include<iostream>
#include<string>
#include <algorithm>
#include <vector>

using namespace std;
typedef vector <string> VECTOR_STRING;

void printVec(VECTOR_STRING& vec)
{
	for(size_t nItem = 0; nItem < vec.size(); nItem++)
	{
		cout << "Name[" << nItem << "] = \" ";
		cout << vec[nItem] << " \" " << endl;
	}
	cout << endl;
}

int main()
{
	VECTOR_STRING vecNames;
	vecNames.push_back("john");
	vecNames.push_back("bob");
	vecNames.push_back("john");
	vecNames.push_back("vctor");
	vecNames.push_back("vctor");
	vecNames.push_back("jim");
	vecNames.push_back("bob");
	vecNames.push_back("jim");

	cout << "the initial contents are:" << endl;
	printVec(vecNames);

	sort(vecNames.begin(), vecNames.end());

	cout << "after sort(), contents are:" << endl;
	printVec(vecNames);

	VECTOR_STRING::iterator iNameTor;
	iNameTor = unique(vecNames.begin(), vecNames.end());

	cout << "after unique(), contents are:" << endl;
	printVec(vecNames);

	cout << "unique return a iterator, point to the first Duplicate element " << endl;
	cout << iNameTor - vecNames.begin() << endl << endl;

	vecNames.erase(iNameTor, vecNames.end()); //删除重复元素
	cout << "after erase(), contents are:" << endl;
	printVec(vecNames);
}


Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐