struggling_learner
struggling_learner

Reputation: 1258

find a value in a C++ map: no matching function for call

Please consider this C++ code:

#include <iostream>
#include <map>


// Global vars
std::map<int, char *>OurMap;
std::map<int, char *>::iterator it;


// prototypes
void populate();
void iterate();

int main(){
    puts("Hello, world!");
    populate();
    iterate();
    return 0;
}

void populate(){
    //char temp[512] = {0};
    for (int i = 0; i < 10; i++){
        char *temp = (char *) calloc(512, sizeof(*temp) );
        snprintf(temp, 256, "temp stuff %d", i);
        OurMap[i] = temp;
        std::cout << "Value: " << OurMap.find(i)->second << std::endl;
    }
}

void iterate(){
    for (auto i : OurMap){
        printf("i: %d\n", i);
        std::cout << "Value: " << OurMap.find(i)->second << std::endl; // <- blows up 
    }
}

C++ maps are bit new to me. Why is iterate() blowing up? I am able to iterate the key, so how do I get the value from elsewhere? I am confused as to why std::cout works in populate() but not in iterate().

mappy.cc:34:42: error: no matching function for call to ‘std::map<int, char*>::find(std::pair<const int, char*>&)’

I am trying to figure out the easiest way I can use my C++ map later in call.

Update:

#include <iostream>
#include <map>


// Global vars
std::map<int, char *>OurMap;
std::map<int, char *>::iterator it;


// prototypes
void populate();
void iterate();

int main(){
    puts("Hello, world!");
    populate();
    iterate();
    return 0;
}

void populate(){
    char temp[512] = {0};
    for (int i = 0; i < 10; i++){
        snprintf(temp, 256, "temp stuff %d", i);
        OurMap[i] = temp;
        std::cout << "Value: " << OurMap.find(i)->second << std::endl;
    }
}

void iterate(){
    for (auto i : OurMap){
        printf("i: %d\n", i);
        auto value = i.second;
        std::cout << "Value: " << value << std::endl;
    }
}

Upvotes: 0

Views: 691

Answers (1)

Cory Kramer
Cory Kramer

Reputation: 118021

When you iterate over a map using a range-based for loop, you are not getting iterators back, but instead the (key, value) pairs themselves. So

for (auto i : OurMap){
    printf("i: %d\n", i);
    std::cout << "Value: " << OurMap.find(i)->second << std::endl; // <- blows up 
}

Should simply be

for (auto i : OurMap){
    printf("i: %d\n", i.first);
    std::cout << "Value: " << i.second << std::endl;
}

Upvotes: 3

Related Questions