c++ unique函數返回值


轉自:https://blog.csdn.net/aggressive_snail/article/details/51332659

std::unique

功能:對有序的容器重新排列,將第一次出現的元素從前往后排,其他重復出現的元素依次排在后面

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

看不懂表達的看看下面這個簡圖:

有序的容器:

1 1 2 3 3 4 4 4 5 6

unique處理過的容器:

unique unique unique unique unique unique 迭代器指向的地址      
1 2 3 4 5 6 1 3 4 4

(上表迭代器是指向倒數第四個數1)

#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);
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM