anarchy99
anarchy99

Reputation: 1023

How to sort a Vector and Remove the Same Value in it?

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

Upvotes: 1

Views: 103

Answers (3)

Avraam Mavridis
Avraam Mavridis

Reputation: 8920

This will do your work but mwerschy's code above is better. 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"));

 }

output will be:

1
2
4
5
8

Upvotes: 0

mwerschy
mwerschy

Reputation: 1708

You can do that with standard functions.

std::sort(vectProjHori.begin(), vectProjHori.end());
vectProjHori.erase(std::unique(vectProjHori.begin(), vectProjHori.end()), vectProjHori.end());

Upvotes: 6

zw324
zw324

Reputation: 27210

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

Upvotes: 1

Related Questions