Hidayat Rzayev
Hidayat Rzayev

Reputation: 389

std::for_each() for a map gives invalid initialization error

I'm relatively new to STL and particularly algorithm library. I'm trying to iterate over a std::multimap, where both key and value are of type std::string, using std::for_each() function and perform some task.

Here's my std::multimap:

std::multimap<std::string, std::string> myMap;
for (int i = 0; i < 5; i++) {
    myMap.insert(std::make_pair("key", "value"));
}

And here is the line with for_each() function:

std::for_each(myMap.begin(), myMap.end(), ask);

The ask() function is defined as following:

void ask(std::pair<std::string, std::string>& entry) {
    // do something...
}

The program gives me the following error:

error: invalid initialization of reference of type 'std::__cxx11::basic_string&' from expression of type 'std::pair, std::__cxx11::basic_string >'

I know that, the problem is on the line with for_each() function and I assume it's because the parameter of ask() function is not correct. But to my knowledge, each entry of the std::multimap is represented as a std::pair, so shouldn't the ask() function take a std::pair object as its parameter?

Upvotes: 2

Views: 248

Answers (3)

Caleth
Caleth

Reputation: 63297

Rather than guessing at the element type of the map, you can ask it directly.

void ask(std::multimap<std::string, std::string>::reference entry) {
    // do something...
}

It might be a good idea to make a type alias for this map type, so that you don't have to repeat it

using myMap_t = std::multimap<std::string, std::string>;

void ask(myMap_t::reference entry) {
    // do something...
}

int main() {
    myMap_t myMap;
    for (int i = 0; i < 5; i++) {
        myMap.insert(myMap_t::value_type("key", "value"));
    }

    std::for_each(myMap.begin(), myMap.end(), ask);
}

Upvotes: 1

Gaurav Sehgal
Gaurav Sehgal

Reputation: 7542

The default allocator used for std::multimap is

std::allocator<std::pair<const Key, T>

So the keys in std::multimap are const which makes the type as

std::pair<const std::string, std::string>

where as ask() expects parameter as a reference to type

std::pair<std::string, std::string>

Change ask() as

void ask(std::pair<const std::string, std::string>& entry)
{
}

Upvotes: 3

Igor Tandetnik
Igor Tandetnik

Reputation: 52621

The element type of std::multimap<std::string, std::string> is std::pair<const std::string, std::string>. Note the const

Upvotes: 6

Related Questions