Monday, March 12, 2012

Practice on C++11(2): tuple, rvalue, auto, lambda

Continue with my previous post about rvalue, auto, lambda, decltype, My second practice is to create a list of objects without knowing too much details. I'll give also 2 styles of code for comparing:

1. Traditional C++ style:

// definition of getTaskList:
// void getTaskLists( std::vector<int>& ids, std::vector<QString>& names );
std::vector<int> ids;
std::vector<QString> names;
PDatabaseManager::instance()->getTaskLists( ids, names );
Q_ASSERT( ids.size() == names.size() );

PLists lists;
for( size_t i = 0; i < ids.size(); ++i )
lists.push_back( PListPtr( new PListSqlite( ids[i], names[i] ) ) );

2. C++11 style, also, leverage algorithms instead of write code by yourself:

// definition of getTaskList:
// std::vector< std::tuple<int, QString> > getTaskLists();
auto&& rawlists = PDatabaseManager::instance()->getTaskLists();

PLists lists;
std::for_each( rawlists.begin(), rawlists.end(), [&]( const std::tuple<int, QString>& i ) {
lists.push_back( PListPtr( new PListSqlite( std::get<0>( i ), std::get<1>( i ) ) ) );
} );

The new style looks more elegant and clean.

1 comment:

  1. Excellent Blog! I would like to thank for the efforts you have made in writing this post. I am hoping the same best work from you in the future as well. I am looking for College Essay Writers I wanted to thank you for this websites! Thanks for sharing.