Samstag, 24. November 2012

Common Algorithms from Wikibooks

Cheers!
I found a nice link from Wikibooks where one can find many common algorithm implementations that occur in frequent tasks of programming:

Although most of them may be implemented in standard libraries of the different languages, it is a great repository of procedures for any purpose. Furthermore you may find it a nice way to learn how these are actually implemented in your framework.

Have a good time while exploring the contents!

Mittwoch, 7. November 2012

Split line in C++

inline vector split(string line, size_t minWordLength) {
  vector ret;
  size_t pos = 0;
  while (pos < line.size()) {
    while (pos < line.size() && !isalpha(line[pos]))
      pos++;
    size_t wordStart = pos;
    while (pos < line.size() && isalpha(line[pos]))
      pos++;
    size_t wordEnd = pos;
    if (wordEnd >= wordStart + minWordLength) {
      string word = line.substr(wordStart, wordEnd - wordStart);
      ret.push_back(word);
    }
  }
  return ret;
}
This inline helper function splits a line of characters (string) and returns a list (vector) of words the line consists of. Given the minWordLength parameter only words with a minimum length of this size will be considered for the output.
The line is split by delimiters being of non-character type like a space or dashes. Of course, one could also use a delimiter as parameter or a list of those to determine the separators within the line...
To use this function string and vector from the STL are required.

Measuring time in C++

inline double startTime() {
  struct timeval tp;
  double sec, usec;
  // Time stamp before the computations
  gettimeofday(&tp, NULL);
  sec = static_cast(tp.tv_sec);
  usec = static_cast(tp.tv_usec) / 1E6;
  return sec + usec;
}

inline double elapsedTime(double starttime) {
  struct timeval tp;
  double sec, usec;
  // Time stamp after the computations
  gettimeofday(&tp, NULL);
  sec = static_cast(tp.tv_sec);
  usec = static_cast(tp.tv_usec) / 1E6;
  // Time calculation (in seconds)
  return sec + usec - starttime;
}
A relatively easy way to measure time in C++ is to use standard linux libraries:
#include <sys/time.h>
#include <sys/types.h>
The first function (that can e.g. be global) returns the system time as double in microseconds. The second one computes the elapsed time according to the measurement given by the first function.
Application example:
...
double start = startTime();
// do something time consuming...
double elapsed = elapsedTime(start);
cout << "The operation took " << elapsed << "µs" << endl;
...