0

[Thank you for the answers, and also sorry for not really understanding all, I guess I'm trying to run yet know know how to walk] If somebody could explain me what happens here, I would really appriciate it! (Just learning C++ and I couldn't really understand by myself/Mr.Google)

string luck;
int choice;
std::map< int, std::string > cookies {
{ 1, "Tomorrow is a day" },
{ 2, "Tomorrow can be cool" },
{ 3, "Summer is coming" }
};
while( cookies.size() ) {
cout << "What cookie do you want? [";
for_each( cookies.begin(), cookies.end(), []( std::map< int, string >::value_type & v ) { cout << v.first << ','; } );
cout << ']';
cin >> choice;

map< int, string >::iterator iter( cookies.find( choice ) );
if( iter == cookies.end() )
    cout << "Sorry, that cookie has been taken" << endl;
else {
    cout << iter->second << endl;
    cookies.erase( iter );
}

If possible, please try to explain it to me like you're explaining how to walk to a child, I really only know the basics of the basic.

Thank you

2 Answers2

2

The #include <ctime> is unneeded in the code you have posted. Removing it would have no effect.

The #include <algorithm> is needed for the std::for_each. The std:: prefix is not needed as some of the arguments are also in the std namespace.

std::for_each is a function that calls the functor given as the third argument on each element between the given begin and end iterators.

[]( std::map< int, string >::value_type & v ) { cout << v.first << ','; } is a lambda function used as the above mentioned functor.

The for_each block is maybe easier to understand written as a range based for loop:

for(auto v: cookies)
{
    cout << v.first << ',';
}
PeterSW
  • 4,921
  • 1
  • 24
  • 35
1
  1. #include <map> you need for using standart stl map container more info here
  2. the same for header <algorithm> it's allow you to use algorithm for_each more info here
  3. Atually I don't know for what header <ctime> needed here but you can read about it here
  4. fore_each

template <class InputIterator, class Function> Function for_each (InputIterator first, InputIterator last, Function fn);

Applies function fn to each of the elements in the range [first,last).

And also more info you also can find in different books

Mr Lister
  • 45,515
  • 15
  • 108
  • 150
segevara
  • 610
  • 1
  • 7
  • 18