Friday, June 24, 2011

Returning a reference to a local/temprorary object without causing a memory leak?(link)

How can it be? Isn't the memory of a local variable inaccessible outside its function?

Read here...

Thursday, June 23, 2011

A bit of C++0x new raw and unicode string literals

C++x0 introduced new string literals: starting with 'u8', 'u', 'U' and 'R'.
'u8' is for utf-8
'u' is for utf-16
'U' is for utf-32
'R' is for raw strings
(Also you can combine those: u8R, uR and UR
#include 
#include 

int main()
{
    std::string old = "c:\\test\\test";
    std::string raw = R"(c:\test\test)";
    std::string utf8 = u8"This is a Unicode Character: \u0160."; 

    std::cout << "old literal: " << old << std::endl;
    std::cout << "new raw literal: " << raw << std::endl;
    std::cout << "new utf-8 literal: " << utf8 << std::endl;

    return 0;
}
Output:
old literal: c:\test\test
new raw literal: c:\test\test
new utf-8 literal: This is a Unicode Character: Š.
Read more here...

Wednesday, June 22, 2011

Performance is a Feature (link)

Read on Coding horror

A bit of C++0x auto keyword

Other cool shortcut in c++x0 is auto keyword it is wrist saver, but don't abuse it. If abused auto could make code unreadable like c# var.

#include <iostream>
#include <vector>

int main()
{
    std::vector<int> vec = { 10, 20, 30, 40 };

    // Compare with pre c++x0 version
    //for(vector<int>::iterator it = vec.begin(); it != vec.end(); it++)
    for(auto it = vec.begin(); it != vec.end(); it++)
    {
        std::cout << *it << std::endl;
    }

    return 0;
}

Tuesday, June 21, 2011

A bit of C++0x std::thread get recommended number of threads for your system

In c++x0 we have this cool function that will tell you recommended number of concurrent threads for your system:

#include <thread>
#include <iostream>

int main()
{
    std::cout << "Recommended number of concurrent threads for your system (hint): "                      
        << std::thread::hardware_concurrency()
        << std::endl;

    return 0;
}

Unfortunately it returns zero for my home computer :)

P.S. Here is more info about std::thread...

Monday, June 20, 2011

Examples of using libcurl from C++ (links)

1. Using libcurl from C++
2. Download file using libcurl in C/C++ (StackOverflow)
3. Simplify Network Programming with libCURL
4. Using LIBCurl with C++ Simple OOP Static Class Example

A bit of C++0x lambda and vector of user defined type sorting

Here is a short example how to using lambdas for sorting vector of user defined types.

#include <vector>
#include <iostream>
#include <algorithm>
#include <iterator>

class Person
{
public:
  Person();
  Person(int a, std::string n);
  Person(const Person& src);

  int age;
  std::string name;
};

Person::Person()
: age(0)
, name("")
{};

Person::Person(int a, std::string n)
: age(a)
, name(n)
{};

Person::Person(const Person& src) 
{ 
  age = src.age; 
  name = src.name; 
}; 
 
int main() 
{ 
    std::vector<Person> a = 
    {
        Person(10, "Person1"), 
        Person(12, "Person2"), 
        Person(12, "Person3") 
    }; 
     
    std::cout << "Before revers sort" << std::endl; 
    std::for_each(a.begin(), a.end(),  
        [](const Person& p) 
        { 
            std::cout << " Person age: " << p.age << " name: " << p.name << std::endl; 
        }); 
 
    std::sort(a.begin(), a.end(),  
        [](const Person& p1, const Person& p2) 
        { 
            if (p1.age > p2.age) return true; 
            if (p1.name.compare(p2.name) > 0) return true; 
            return false; 
        }); 
 
    std::cout << "After revers sort" << std::endl; 
    std::for_each(a.begin(), a.end(),  
        [](const Person& p) 
        { 
            std::cout << " Person age: " << p.age << " name: " << p.name << std::endl; 
        }); 
}  

Friday, June 17, 2011

A bit of C++0x lambda and vector sort (reverse sort)

Here is example how to sort vector by using lambdas (You can compare it with old post where used std::greater() for this, in my opinion lambdas are cleaner).

#include <vector>
#include <iostream>
#include <algorithm>
#include <iterator>

int main()
{
    std::vector<int> a = { 10, 90, 50, 20, 30, 5 };
    std::vector<int> b = { 10, 90, 50, 20, 30, 5 };

    std::sort(a.begin(), a.end(),
        [](const int& a, const int& b)
        {
            return a < b;
        });

    std::copy(a.begin(), a.end(), std::ostream_iterator<int>(std::cout, " "));
    std::cout << std::endl;

    std::sort(b.begin(), b.end(),
        [](const int& a, const int& b)
        {
            return a > b;
        });

    std::copy(b.begin(), b.end(), std::ostream_iterator<int>(std::cout, " "));
    std::cout << std::endl;
}

SleepSort implementation with c++0x std::thread

Here it is the Sleep Sort

#include <thread>
#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>

void sleep_sort(int n)
{
    std::this_thread::sleep_for(std::chrono::milliseconds(n));
    std::cout << n << " ";
}

int main()
{
    std::vector<int> a = {1500, 200, 100, 300, 400, 300};

    std::vector<std::thread> threads;
    for(std::vector<int>::iterator it = a.begin(); it != a.end(); it++)
    {
        threads.push_back(std::thread(sleep_sort, *it));
    }

    std::for_each(threads.begin(), threads.end(),
        std::mem_fn(&std::thread::join));

    std::cout << std::endl;

    return 0;
}

Thursday, June 16, 2011

A bit of C++0x std::thread and passing parameters

One small bit from C++0x I want to share with you today is:

you can't use std::thread constructor to pass parameters by reference, all parameters will be passed by value!

Here is a source to demonstrate this:
#include 
#include 

void inc(int& number)
{
    std::cout << "In thread before increment: " << number << std::endl;

    number = number + 1;

    std::cout << "In thread after increment: " << number << std::endl;
}

int main()
{
    int n = 10;

    std::cout << "Before inc: " << n << std::endl;

    std::thread worker(inc, n);
    worker.join();

    std::cout << "After inc: " << n << std::endl;

    return 0;
}
Small note about compiling: I use GNU Compiler Collection (GCC) version 4.5 on Linux (mingw port don't support std::thread yet).
g++ -std=c++0x -lpthread test.cpp -o test
./test
And here is output:
Before inc: 10
In thread before increment: 10
In thread after increment: 11
After inc: 10
UPDATED!!! solution is simple: use the std::ref, Luke!
#include 
#include 

void inc(int& number)
{
    std::cout << "In thread before increment: " << number << std::endl;

    number = number + 1;

    std::cout << "In thread after increment: " << number << std::endl;
}

int main()
{
    int n = 10;

    std::cout << "Before inc: " << n << std::endl;

    std::thread worker(inc, std::ref(n));
    worker.join();

    std::cout << "After inc: " << n << std::endl;

    return 0;
}
and the output is:
Before inc: 10
In thread before increment: 10
In thread after increment: 11
After inc: 11

Wednesday, June 15, 2011

Monday, June 13, 2011

Facebook Make Me Sad (link)

read here...

Quote of The Day - 2011-06-13

Watch your thoughts, for they become words.
Watch your words, for they become actions.
Watch your actions, for they become habits.
Watch your habits, for they become your character.
Watch your character, for it becomes your destiny.

read here...

Tuesday, June 7, 2011

C# capitalize each word in string

One day I stumbled on this problem in my work so I have done some thinking and searched for simple solution. I have collected all implementation I could find created benchmark and measured performance.

Let take look at source code
using System;
using System.Diagnostics;
using System.Globalization;
using System.Text;
using System.Text.RegularExpressions;

namespace ToTitleCase
{
 class MainClass
 {
  const string test = "How to capitalize the first character of each word? Other characters should be lower case.";
  const int N = 100000;
  
  public static string BadToTitleCase (string str)
  {
   StringBuilder result = new StringBuilder ();
   str = str.ToLower ();
   string [] names = str.Split (' ');

   for (int name_index = 0; name_index < names.Length; name_index++) {
    int i = 0;
    while (char.IsWhiteSpace(names[name_index][i]) && i < names[name_index].Length) {
     i++;
    }
    StringBuilder sb = new StringBuilder (names [name_index]);
    sb [i] = names [name_index].ToUpper () [i];
    result.Append (sb.ToString ());
    if (name_index < names.Length - 1)
     result.Append (" ");
   }
   return result.ToString ();
  }
  
  public static String BadToTitleCase2 (string str)
  {
   String[] split;

   split = str.Split (' ');
   str = String.Empty;
   foreach (String part in split) {
    Char[] chars;

    chars = part.ToCharArray ();
    if (chars.Length > 0) {
     chars [0] = ((new String (chars [0], 1)).ToUpper ().ToCharArray ()) [0];
    }
    str += new string (chars) + ' ';
   }
   str = str.Substring (0, str.Length - 1);
   return (str);
  }

  public static string SimpleToTitleCase (string str)
  {
   string result = null;
         
   if (!string.IsNullOrEmpty (str)) {
    string[] words = str.Split (' ');
    for (int i = 0; i < words.Length; i++) {
     var s = words [i];
     if (s.Length > 0) {
      words [i] = s [0].ToString ().ToUpper () + s.Substring (1);
     }     
    }
    result = string.Join (" ", words);
   }
   
   return result;
  }

  public static string NetToTitleCase (string str)
  {
   return CultureInfo.CurrentCulture.TextInfo.ToTitleCase (str.ToLower ());
  }
  
  public static string BufferToTitleCase (string str)
  {
   char[] array = str.ToCharArray ();

   int count = array.Length;
   if (count > 0)
    array [0] = char.ToUpper (array [0]);

   for (int i = 1; i < count; i++) {
    if (char.IsWhiteSpace (array [i - 1]))
     array [i] = char.ToUpper (array [i]);
    else
     array [i] = char.ToLower (array [i]);
   }

   return new string (array);
  }
  
  public static string StringBuilderToTitleCase (string str)
  {
   if (str == null)
    throw new ArgumentNullException ("value");   
   
   if (str.Length == 0)
    return str;
   
   StringBuilder sb = new StringBuilder (str.Length);
   // Upper the first char.
   sb.Append (char.ToUpper (str [0]));
   for (int i = 1; i < str.Length; i++) {
    // Get the current char.
    char c = str [i];
    
    // Upper if after a space.
    if (char.IsWhiteSpace (str [i - 1]))
     c = char.ToUpper (c);
    else
     c = char.ToLower (c);
    
    sb.Append (c);
   }
   
   return sb.ToString ();
  }
  
  public static string StringBuilderToTitleCase2 (string str)
  {
   if (str == null)
    throw new ArgumentNullException ("value");
  
   if (str.Length == 0)
    return str;
  
   StringBuilder result = new StringBuilder (str);
   result [0] = char.ToUpper (result [0]);
   for (int i = 1; i < result.Length; ++i) {
    if (char.IsWhiteSpace (result [i - 1]))
     result [i] = char.ToUpper (result [i]);
    else
     result [i] = char.ToLower (result [i]);
   }
   return result.ToString ();
  }
  
  static string CapitalizeString (Match str)
  {
   string strTemp = str.ToString ();
   strTemp = char.ToUpper (strTemp [0]) + strTemp.Substring (1, strTemp.Length - 1).ToLower ();
   return strTemp;
  }
  
  public static string RegexToTitleCase (string str)
  {
   return Regex.Replace (str, @"\w+", new MatchEvaluator (CapitalizeString));
  }
  
  public static void Main (string[] args)
  {
   Stopwatch watch = new Stopwatch ();
   watch.Start ();
   
   long tPrev = watch.ElapsedMilliseconds;
   for (int i = 0; i < N; i++) {
    string last = BufferToTitleCase (test);
   }
   Console.WriteLine ("BufferToTitleCase time: " + (watch.ElapsedMilliseconds - tPrev));
   
   tPrev = watch.ElapsedMilliseconds;
   for (int i = 0; i < N; i++) {
    string last = BadToTitleCase (test);
   }
   Console.WriteLine ("BadToTitleCase Time: " + (watch.ElapsedMilliseconds - tPrev));
   
   tPrev = watch.ElapsedMilliseconds;
   for (int i = 0; i < N; i++) {
    string last = BadToTitleCase2 (test);
   }
   Console.WriteLine ("BadToTitleCase2 Time: " + (watch.ElapsedMilliseconds - tPrev));
   
   tPrev = watch.ElapsedMilliseconds;
   for (int i = 0; i < N; i++) {
    string last = NetToTitleCase (test);
   }
   Console.WriteLine ("NetToTitleCase Time: " + (watch.ElapsedMilliseconds - tPrev));
   
   tPrev = watch.ElapsedMilliseconds;
   for (int i = 0; i < N; i++) {
    string last = StringBuilderToTitleCase (test);
   }
   Console.WriteLine ("StringBuilderToTitleCase Time: " + (watch.ElapsedMilliseconds - tPrev));

   tPrev = watch.ElapsedMilliseconds;
   for (int i = 0; i < N; i++) {
    string last = StringBuilderToTitleCase2 (test);
   }
   Console.WriteLine ("StringBuilderToTitleCase2 Time: " + (watch.ElapsedMilliseconds - tPrev));
   
   tPrev = watch.ElapsedMilliseconds;
   for (int i = 0; i < N; i++) {
    string last = SimpleToTitleCase (test);
   }
   Console.WriteLine ("SimpleToTitleCase Time: " + (watch.ElapsedMilliseconds - tPrev));
   
   tPrev = watch.ElapsedMilliseconds;
   for (int i = 0; i < N; i++) {
    string last = RegexToTitleCase (test);
   }
   Console.WriteLine ("RegexToTitleCase Time: " + (watch.ElapsedMilliseconds - tPrev));
   
   watch.Stop ();
   watch = null;
   
   Console.WriteLine ("Done. Press any key...");
   Console.ReadLine ();
  }
 }
}
Benchmark results
My Conclusions
  • RegexToTitleCase: for such simple text processing task regular expressions is overkill also it is clear that calling delegate function negatively effects performance;
  • BadToTitleCase and BadToTitleCase2: those implementation allocates new temporary objects for string processing and the source code is not elegant;
  • SimpleToTitleCase: wisely used string.Join no need to allocate new temporary objects for string processing this improves performance;
  • NetToTitleCase: uses CultureInfo.CurrentCulture.TextInfo.ToTitleCase which is native implementation so no comments here;
  • BufferToTitleCase: is my favorite because of simplicity of code and performance (avoids allocation of new temporary objects for string processing by using string.ToCharArray method).


P.S. If you have some better or worse implementations, please contact me, I would be very interesting to include those in my benchmark.

Quote of The Day - 2011-06-07

Google's plan, for example, was simply to create a search site that didn't suck. They had three new ideas: index more of the Web, use links to rank search results, and have clean, simple web pages with unintrusive keyword-based ads. Above all, they were determined to make a site that was good to use. No doubt there are great technical tricks within Google, but the overall plan was straightforward.

- Paul Graham

A brief Sony password analysis (link)

We know passwords are too short, too simple, too predictable and too much like the other ones the individual has created in other locations. Read here...

Friday, June 3, 2011