algorithm之unique

  1. #include<iostream>
  2. #include<algorithm>
  3. usingnamespace std;
  4. /**< unique函数的算法思想 */
  5. vector<int>::iterator uniqueElements(vector<int>::iterator begPos,vector<int>::iterator endPos)
  6. {
  7. auto currPos = begPos +1;
  8. while(currPos != endPos)
  9. {
  10. if(*begPos !=*currPos)
  11. *(++begPos)=*(currPos++);
  12. else
  13. ++currPos;
  14. }
  15. return begPos+1;
  16. }
  17. int main()
  18. {
  19. vector<int> intVector;
  20. for(int i =0; i <20;++i)
  21. {
  22. intVector.push_back(rand()%10);
  23. }
  24. for(auto val : intVector)
  25. {
  26. cout << val <<" ";
  27. }
  28. cout << endl;
  29. sort(intVector.begin(), intVector.end());
  30. for(auto val : intVector)
  31. {
  32. cout << val <<" ";
  33. }
  34. cout << endl;
  35. auto end_unique = unique(intVector.begin(), intVector.end());
  36. /**< 可以查看算法,unique并不是简单的将重复的元素放置到最后面去 */
  37. for(vector<int>::iterator it = intVector.begin(); it != intVector.end();++it)
  38. {
  39. if(it == end_unique)
  40. cout <<"##";
  41. cout <<*it <<" ";
  42. }
  43. cout << endl;
  44. intVector.erase(end_unique,intVector.end());
  45. for(auto val:intVector )
  46. cout << val <<" ";
  47. cout << endl;
  48. return0;
  49. }
 





posted @ 2015-07-16 19:10  指上弹兵赵小括  阅读(336)  评论(0编辑  收藏  举报