1

I have a vector containing data such as: 15,27,40,50,15,40

I want to sort it and remove the same value, so the output after the sort should be: 15,27,40,50

I've tried several ways such:

std::sort(vectProjHori.begin(),vectProjHori.end());
for (std::vector<int>::iterator it=vectProjHori.begin(); it!=vectProjHori.end(); ++it)
{
    if(it+1 != it)
    {
        std::cout << ' ' << *it;
    }
}

But, it can't remove the same value in the vector. I really hope someone would like to give an efficient way how to do it.

Any help would be highly appreciated. Thank you

4

3 回答 3

7

You can do that with standard functions.

std::sort(vectProjHori.begin(), vectProjHori.end());
vectProjHori.erase(std::unique(vectProjHori.begin(), vectProjHori.end()), vectProjHori.end());
于 2013-05-25T14:51:55.313 回答
1

it + 1 sure is not it; you need to first dereference before comparison.

于 2013-05-25T14:51:21.313 回答
0

这将完成您的工作,但上面 mwerschy 的代码更好。C++11

#include <iostream>
#include <algorithm>
#include <iterator>


int main() { 

  std::vector<int> v={1,2,8,4,5,5};
  std::sort(v.begin(),v.end());
  auto it=std::unique(v.begin(),v.end());
  v.resize(std::distance(v.begin(),it));
  std::copy(v.begin(),v.end(),std::ostream_iterator<int>(std::cout,"\n"));

 }

输出将是:

1
2
4
5
8
于 2013-05-25T14:52:12.453 回答