Recently, i learnt about the STL types and templates and we were given a challenge as part of practicing the STL and getting used to using it:
- Iterate over a
std::map<std::string, size_t>
- Print its contents
Restrictions:
Can only use:
std::vector
,std::map
,std::string
,std::algorithm
,std::functional
Cannot define complex types nor templates
Cannot use the
. (member access), -> (member access via pointer), * (dereference) operators
Cannot use
for, while, do-while nor if-else, switch
and other conditionalsCan use
std::for_each
and other functions of function templates to iterate over collection of elementsNo lambdas
No
std::cout
,std::cerr
,std::ostream
etc.No auto types
Can use other STL templates so long as they are included in the headers described at (1)
Allowed to use these functions:
void print(const std::string& str)
{
std::cout << str << std::endl;
}
std::string split(const std::pair<std::string, size_t> &r)
{
std::string name;
std::tie(name, std::ignore) = r;
return name;
}
Originally, i had wanted to use std::for_each(std::begin(mymap), std::end(mymap), print)
to iterate over the map and then use the print function to print out the contents. Then i realised that i am actually working with std::pair<std::string, size_t>
which made me consider the use of std::bind
and std::tie
to break the std::pair
up. But since i THINK i need to do it inside the std::for_each
expression, how can i break up the std::pair
while also call print on the elements?
I have also considered using Structured Binding
but i am not allowed to use auto
.
So, the question is, how do i make use of the STL to iterate the map to extract then print out the keys using the helper functions provided? Obviously, without the restrictions the challenge would have been very easy, but i am at a loss as to what kind of functions in the STL are appropriate in light of this.