Algorithms for working with map C++

The essence of the task: to implement for map 5 algorithms sort, copy, none_of, find_if, copy_if.

I started to understand, and I found examples only for vector.

You can just write an example of how to work with these algorithms using map, not vector.

Author: Vlad from Moscow, 2015-11-08

1 answers

Of these five standard algorithms, you can apply only the algorithms to the container std::map std::copy, std::none_of, std::find_if and std::copy_if.

You can't apply the standard algorithm std::sort, because the container std::map is in turn a sorted container by key (you can't change the order of the elements), and secondly, the standard algorithm std::sort requires a random access iterator, and std::map has only a two-way sequential iterator.

Also keep in mind that this container has its own methods that perform the search, such as, find, lower_bound, upper_bound and equal_range.

Here is an example of applying some of the listed standard algorithms to a container std::map

#include <iostream>
#include <iomanip>
#include <map>
#include <algorithm>
#include <string>
#include <functional>

int main()
{
    std::map<int, std::string> m;

    m[0] = "Peter";
    m[1] = "John";
    m[2] = "Bob";
    m[3] = "Fred";

    for ( const auto &p : m ) std::cout << p.first << ": " << p.second << std::endl;

    std::cout << std::endl;

    std::map<int, std::string> m2;

    std::copy( m.begin(), m.end(), std::inserter( m2, m2.end() ) );

    for ( const auto &p : m2 ) std::cout << p.first << ": " << p.second << std::endl;

    std::cout << std::endl;

    m2.clear();

    std::copy_if( m.begin(), m.end(), std::inserter( m2, m2.end() ), 
                  []( const std::pair<int, std::string> &p ) { return p.first % 2; } );

    for ( const auto &p : m2 ) std::cout << p.first << ": " << p.second << std::endl;

    std::cout << std::endl;

    std::cout << "Neither name is less than 3 characters: "
              << std::boolalpha
              << std::none_of( m.begin(), m.end(), 
                               []( const std::pair<int, std::string> &p ) { return p.second.size() < 3; } )
              << std::endl;

    std::string name = "John";

    auto it = std::find_if( m.begin(), m.end(), 
                            [&name]( const std::pair<int, std::string> &p ) { return p.second == name; } );

    if ( it != m.end() )
    {
        std::cout << it->second << " has key " << it->first << std::endl;
    }
    else
    {
        std::cout << "Name \"" << name << "\" is not found" << std::endl;
    }        

    return 0;
}

Output to the console:

0: Peter
1: John
2: Bob
3: Fred

0: Peter
1: John
2: Bob
3: Fred

1: John
3: Fred

Neither name is less than 3 characters: true
John has key 1
 3
Author: Vlad from Moscow, 2015-11-08 22:15:46