c++ - Number of unique elements in a vector -


if have vector of floats {1.2,1.2,1.2,1.3,1.4} , have find out number of unique elements, how can it?

i new c++ , don't know how use iterators. thanks!

edit: did this:

sort(arra.begin(),arra.end());     vector <float>::iterator = arra.begin();     while ( != arra.end() )     {         temp1 = *it;         cout<<temp1<<"\n";         it++;         while (*it == temp1)         {             it++;             cout<<*it<<"\n";         }         count++;     } 

but gives wa.

one of approaches following

#include <iostream> #include <vector> #include <set>  int main()  {     std::vector<double> v = { 1.2, 1.2, 1.2, 1.3, 1.4 };      std::cout << "number of unique elements "               << std::set<double>( v.begin(), v.end() ).size()               << std::endl;      return 0; } 

the output is

number of unique elements 3 

if vector sorted , not empty can use following approach

#include <iostream> #include <vector> #include <numeric> #include <iterator> #include <functional>  int main()  {     std::vector<double> v = { 1.2, 1.2, 1.2, 1.3, 1.4 };      auto n = 1 + std::inner_product( std::next( v.begin() ), v.end(),                                       v.begin(), size_t( 0 ),                                      std::plus<size_t>(),                                       std::not_equal_to<double>() );      std::cout << "number of unique elements " << n << std::endl;      return 0; } 

or straightforward approach

#include <iostream> #include <vector>  int main()  {     std::vector<double> v = { 1.2, 1.2, 1.2, 1.3, 1.4 };      size_t n = 0;      if ( v.begin() != v.end() )     {         ++n;         ( auto current = v.begin(), prev = v.begin();               ++current != v.end(); ++prev )         {             if ( !( *prev < *current ) && !( *current < *prev ) ) ++n;         }                }      std::cout << "number of unique elements " << n << std::endl;      return 0; } 

Comments

Popular posts from this blog

google chrome - Developer tools - How to inspect the elements which are added momentarily (by JQuery)? -

angularjs - Showing an empty as first option in select tag -

php - Cloud9 cloud IDE and CakePHP -