Follow by Email

Thursday, May 24, 2007

STL Clips 1

Guess the output of that program:


#include <iostream>
#include <algorithm>
using namespace std;

int main()
{
string str = "<F";
transform(str.begin(),str.end(),str.begin(),bind2nd(plus<char>(),-2));
cout << str;
return 0;
}


Output (highlight to see):
:D

2 comments:

MeshMesh said...

Oh coool :D so u can now make program for emoticons ..that's gr8! At first, I saw the output D ...that confused me u (who call for simplicity :D) definitely won't write lines of code to display a D when u can write a single line so I "cleaned my glasses for better view" :D

Mohammad Nabil said...

I see you started to use Google Reader :D
The output is ":D" btw.
And btw this is simplicity in the sense of expressiveness and ( some other word i really try to remember !, it means saying what u want simply and accurately ).
Example:
transfrom(BIGstr.begin(),BIGstr.end(),smallstr.begin(),tolower);
tolower is a defined function is ISO C. It simply means make the BIGstr to lower case and put the result in smallstr.
It saved you a loop.
One of the powers of STL is extensibility. You can actually put any function (or functor <<<) or composite functors to make operations that you may think you will have to write the loop yourself to do it.
for example from
http://www.sgi.com/tech/stl/functors.html
list<int> L;
...
list<int>::iterator new_end =
remove_if(L.begin(), L.end(),
compose2(logical_and<bool>(),
bind2nd(greater<int>(), 100),
bind2nd(less<int>(), 1000)));
L.erase(new_end, L.end());
this code will simply remove elements greater than 100 and less than 1000 from any non-const iteratable container (not just list, includes : slist, map, etc.).
STL is a great world, expressive power is the key.