Erase all value in a vector more than three standard deviations less than the mean with erase() remove_if() and bind2nd : vector erase « vector « C++ Tutorial






#include <algorithm>
#include <cmath>
#include <functional>
#include <iostream>
#include <list>
#include <numeric>
#include <vector>

using namespace std;

template <class T>
void print(T& c){
   for( typename T::iterator i = c.begin(); i != c.end(); i++ ){
      std::cout << *i << endl;
   }
}

int main( )
{
   const float a[] = { 1, 1.3, 1.5, 0.9, 0.1, 0.2};

   // create and initialize vector with above data
   vector<float> data( a,a + sizeof( a ) / sizeof( a[0] ) );

   cout << "DATA VECTOR HAS " << data.size() << " ELEMENTS\n";
   print( data  );

   // compute the mean
   float mean = accumulate( data.begin(), data.end(), 0.0f )/ data.size();

   // subtract the mean from every data point
   vector<float> zero_mean( data );
   transform( zero_mean.begin(), zero_mean.end(), zero_mean.begin(),bind2nd( minus<float>(), mean ) );

   // compute the sample standard deviation
   float deviation = inner_product( zero_mean.begin(),zero_mean.end(), zero_mean.begin(), 0.0f );
   deviation = sqrt( deviation / ( data.size() - 1 ) );

   const int num_deviations = 3;
   // erase all points more than three standard deviations less than the mean
   data.erase( remove_if( data.begin(), data.end(),bind2nd( less<float>(), mean - num_deviations * deviation ) ),data.end() );

}








16.13.vector erase
16.13.1.Remove(delete) all elements in the vector
16.13.2.Erase first element
16.13.3.erase the numbers 2 through 5 in v1
16.13.4.insert and erase.
16.13.5.Use unique_copy to remove duplicate words
16.13.6.Erase adjacent duplicates
16.13.7.Erase all value in a vector more than three standard deviations greater than the mean
16.13.8.Erase all value in a vector more than three standard deviations less than the mean with erase() remove_if() and bind2nd