The adjacent difference of the vector : Algorithm « vector « C++ Tutorial






#include <vector> 
#include <iostream> 
#include <numeric>   
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() { 

  vector<double> vec1(4, 2.0);  // Length 4, all values == 2.0 
  vector<double> vec2(4, 4.0);  // Length 4, all values == 4.0 

  double init = 0.0; 
  double summation = accumulate (vec1.begin(), vec1.end(), init); 

  cout << "Sum of elements in vector 1: " << summation << endl; 

  double ip = inner_product(vec1.begin(), vec1.end(), vec2.begin(), init); 
  cout << "Inner product of vec1 and vec2: " << ip << endl; 

  int size = 6; 
  int seed_value = 2; 
  vector<int> vec3(size, seed_value); 
  vector<int> result(size); 
  partial_sum(vec3.begin(), vec3.end(), result.begin()); 

  print(result); 

  int sz = 10; 
  int value = 2; 
  vector<int> vec4(sz); 

  vector<int>::iterator it; 
  for (it = vec4.begin(); it != vec4.end(); it++) 
  { 
    (*it) = value; 
    value += 1; 
  } 
  vector<int> result2(vec4.size()); 
  adjacent_difference(vec4.begin(), vec4.end(), result2.begin()); 
  cout << "The adjacent difference of the vector vec4\n"; 

  print(result2); 

  return 0; 
}








16.32.Algorithm
16.32.1.Using the for_each() Algorithm
16.32.2.find_if, bind2nd and greater_equal
16.32.3.Mutating Sequence Algorithm
16.32.4.Use the count_if algorithm with the unary predicate IsEven
16.32.5.Use count to determine the number of '0's in the vector
16.32.6.merge the elements of NumbersVestor and NumbersList and place the results in NumbersDeque
16.32.7.shuffle the elements in a random order
16.32.8.Fill elements in a vector with custom generator
16.32.9.random number generation in quantitative finance
16.32.10.Inner product of a vector and another vector
16.32.11.The adjacent difference of the vector
16.32.12.for_each element in a vector apply custom function
16.32.13.Find the first element in the range (first, last + 1) that matches value