Saturday, May 17, 2008

The elegance of C++

Yes, C++ is my favorite language; it's one of the first I learned (surely the first OO language I learned) and I kept using it through the years. Of course, for network applications I used Java, since I admit it's easier for that context; but when I can, I always go back to C++.

One of the things I like most is the STL library; it uses generic programming extensively with nice and elegant results; by the way, we're talking about true generic programming... not the one provided by Java, which is very little generic :-)

Last day I had to copy the elements of a list into a set, and I was about to write the classical for loop using iterators, especially for printing the results to the screen, and then I said to myself "what are you doing? You're not using Java! You're in C++ now, you can use generic algorithms!"

You can use the insert method of the class set that takes two generic iterators and you can use the copy algorithm to "copy" all the elements of iterators into the standard output (by using an ostream_iterator).

It surely is a matter of taste (and de gustibus non est disputandum), but I find the resulting code very very elegant... probably stl lacks some functionalities when it comes to for_each loops that need to invoke class methods with some parameters... but you can always rely on the fantastic boost libraries!

#include <set>
#include <list>
#include <iostream>
#include <algorithm>
#include <iterator>

using namespace std;

int main() {
list<int> mylist;
set<int> myset;

mylist.push_back(10);
mylist.push_back(11);
mylist.push_back(1);
mylist.push_back(2);
mylist.push_back(10);
mylist.push_back(10);
mylist.push_back(10);
mylist.push_back(2);
mylist.push_back(20);

myset.insert(100);
myset.insert(2);

cout << "list: " << endl;
copy(mylist.begin(), mylist.end(), ostream_iterator<int>(cout, "\n"));

cout << "set: " << endl;
copy(myset.begin(), myset.end(), ostream_iterator<int>(cout, "\n"));

myset.insert(mylist.begin(), mylist.end());

cout << "set after insertion: " << endl;
copy(myset.begin(), myset.end(), ostream_iterator<int>(cout, "\n"));

return 0;
}

4 comments:

Anonymous said...

#!/usr/bin/env python
a = list((1,2,3,3,3,4,5))
b = set(a)

Anonymous said...

PUAH!!!

betto said...

and what about types? As I said previously on this blog, I love statically typed languages and definitely dislike dynamically typed ones... so, as for me, python is no competition...

alagala said...

You could have answered him with the following code. Compact as Python, yet statically typed! ;-)

// Example program
#include
#include
#include
#include
#include

int main()
{
std::list mylist { 10, 11, 1, 2, 10, 10, 10, 2, 20 };
std::set myset { mylist.begin(), mylist.end() };

std::copy(myset.begin(), myset.end(), std::ostream_iterator(std::cout, "\n"));

return 0;
}