-1

In this assignment, I'm making an application where a user inputs a phone number whether it be letters or not.

I've tried using the const on maps or vector to see if it fixes the problem, but I think it just created more errors.

Here's the code that I think that causes some problems

std::vector<int> mappednums;
    for (char& achar : word) {
        auto itr = std::find_if(lookupmap.begin(), lookupmap.end(), [&](std::pair<int, std::vector<char>>& aPair)->bool
            {

                auto itr = std::find_if(aPair.second.begin(), aPair.second.end(), [&](char& ch) {
                    return ch == achar;
                    });

                if (itr != aPair.second.end()) {
                    return true;
                }
                });
        if (itr != lookupmap.end()) {
            mappednums.push_back(itr->first);
        }

I expected this to find a pair, but it gives me an error saying it cannot convert argument 1 from the code above. Here's the error:

'bool main::<lambda_06927067034dcc4076cc2514a7e290fe>::operator ()(std::pair<int,std::vector<char,std::allocator<char>>> &) const': cannot convert argument 1 from 'std::pair<const _Kty,_Ty>' to 'std::pair<int,std::vector<char,std::allocator<char>>> &'
Mooing Duck
  • 64,318
  • 19
  • 100
  • 158

2 Answers2

1

Short answer: Add const before int in first lambda's parameter:

[&](std::pair<const int, std::vector<char>>& aPair)->bool

Long answer:

According to the std::map reference map<K, V>::iterator is an iterator to a map<K, V>::value_type, and map<K, V>::value_type is pair<const K, V> (is your case is pair<const int, vector<char>>).

The problem is that you try to bind pair<int, vector<char>> & reference to the values of type pair<const int, vector<char>>. If you could do so, you would be able to mutate the keys in a map, completely destroying map's internal structure. So you are not allowed to mutate them, and it is denoted as const in pair<const int, vector<char>>.

Yuri Kovalenko
  • 1,325
  • 9
  • 19
0

You haven't declared the parameter correctly for your lambda. It should be

[&](std::pair<const int, std::vector<char>>& aPair)

Note the const int as the first type of the pair. The value type of a map (and what you get when you dereference a map iterator) has the first member of the pair constant, since changing the key value once it is the map can potentially break the sorting in the tree structure used to hold the map.

One way to avoid problems like this is to use

[&](LookupMapType::value_type &aPair)

(where 'LookupMapType' is the type of lookupmap).

If your compiler supports C++14 or later (and you enable it, if needed), you can simplify that some more to

[&](auto &aPair)
1201ProgramAlarm
  • 32,384
  • 7
  • 42
  • 56