waqqasfarooq.com

  • Increase font size
  • Default font size
  • Decrease font size
Home Useful Code Snippets

Useful Code Snippets

Remove elements from std::vector and std::list

E-mail Print PDF
User Rating: / 9
PoorBest 

Often times you would want to filter out some data from your collection of a vector or a list. The following code snippet shows a quick and fool proof way of doing that:

 

Bind and find (C++ std bind2nd and find_if example)

E-mail Print PDF
User Rating: / 12
PoorBest 

STL provides us with very useful algorithms and utilities. You start enjoying the usefulness of programming when you reap the benefits of these utils. In this article I will try to show you the usefulness of the std::bind2nd function. The basic idea behind bind2nd (or bind1st) is that it will take a binary function along with one of the parameters and bind it in a function object. This function object will be then a unary function. If all this sounds confusing then don't worry too much about it. You should read these first few lines again after you go through the example and hopefully then this will all make sense.

I have a created an example to illustrate how you can use std::find_if and std::bind2nd to search through a STL collection. I've tries to keep the example simple. Please let me know if you have trouble understanding the code. In this example we will create a collection of Person and we will search through this collection.

Example Description:

 

Getting random element from std collection

E-mail Print PDF
User Rating: / 11
PoorBest 

The following code snippet gives a quick way of selecting an element at random from a std collection.