SFML community forums

General => General discussions => Topic started by: Canvas on December 02, 2013, 09:22:13 pm

Title: SFML 2.0 C++ book questions
Post by: Canvas on December 02, 2013, 09:22:13 pm
Hey there people,

I have purchases the SFML 2.0 book (a while ago), it is going great, but some pieces of code in the book i don't 100% understand. I'm hoping someone here can just help me out with some parts,

On page 57 there is this piece of code

        auto found = std::find_if(mChildren.begin(), mChildren.end(),
                [&] (Ptr& p) -> bool { return p.get() == &node; });

found is a auto variable which is?
i understand the std::find_if
but what does this line mean? [&] (Ptr& p) -> boo
and return p.get() == &node;???

I will also be asking more questions as I see them
Title: Re: SFML 2.0 C++ book questions
Post by: Kanefa on December 02, 2013, 09:42:13 pm
These are both C++ 11 features.   

The auto keyword deduces the type from the initializer.  In this case std::find_if returns an iterator of type std::vector<Ptr>::iterator.

The next feature is a lambda expression.  This allows you to create an anonymous function. 

Quote
[&]

Captures all automatic variables in the lambda body by reference.

Quote
(Ptr& p)
Is simply the parameter list for the lambda expression (same as in named functions).  In this case find_if is iterating through a vector of Ptrs feeding your lambda expression with them.

Quote
-> bool

Is the optional return type of the lambda expression.

Quote
return p.get() == &node
Compares the addresses of the nodes and returns true if they match.  p is a unique _ptr and get() returns a pointer to the managed object and the address operator returns the address of the node leaving two addresses to be checked for equality. 

Title: Re: SFML 2.0 C++ book questions
Post by: Nexus on December 02, 2013, 10:33:36 pm
By the way, these things are explained the first time they are used in the book. There are several C++11 boxes that briefly introduce new features.