Wednesday, December 5, 2012

Using Algorithm Library and Functional

Just an example to show the utility of the library algorithm.

#include <iostream>
#include <algorithm>
#include <vector>
#include <functional>

using namespace std;

int op_increase (int i) { return ++i; }
int op_sum (int i, int j) { return i+j; }

void inc(int& val){
    static int i = 0;
    val += i;
    i += 10;
}

ostream& operator<<(ostream& out, const vector<int>& a){
    for (int i = 0; i < a.size(); i++)
        out << a[i] << ", ";
    
    out << endl;
    return out;
}
int main () {
  vector<int> first(5);
  vector<int> second;
  vector<int> result;
  
  second.resize(first.size());    
  result.resize(first.size());

  // set some values:
  for_each(first.begin(), first.end(), inc); 
  for_each(second.begin(), second.end(), inc);
  
  cout << first << second << result;

  transform (first.begin(), first.end(), result.begin(), op_increase);
  cout << result;
  
  transform (first.begin(), first.end(), second.begin(), result.begin(), op_sum);
  cout << result;

  vector<int> lenghts;
  vector <string*> numbers;

  // populate vector of pointers:
  numbers.push_back ( new string ("one") );
  numbers.push_back ( new string ("two") );
  numbers.push_back ( new string ("three") );
  numbers.push_back ( new string ("four") );
  numbers.push_back ( new string ("five") );

  lenghts.resize(numbers.size() );

  transform (numbers.begin(), numbers.end(), lenghts.begin(), mem_fun(&string::length) );
  cout << lenghts;

  system("pause");
  return 0;
}

Also, it is possible to use mem_fun_ref instead of mem_fun without the need of use a vector of pointers to strings and just use strings instead of,

Thus, in conclusion, it's very interesting to know how to use this libraries because allow you to work more efficiently and do the same work in less time.

No comments:

Post a Comment