简体   繁体   中英

How can I write a function that, given a pointer to a map, returns a pointer to a specific element in the map?

I have a map:

std::map<int,float> m1;

I want to pass a pointer to that map to a function that will iterate over the map and return a pointer to a particular element in that map based on some condition.

float *foo(map<int,float> *m1){
  float *result;
  for(map<int,float>::iterator it = m1->begin(); it != m1->end(); it++)
    {
      if (condition)
        {
          result = &(it->second);
          break;
        }
    }
  return result;
}

This code did not compile. I'm having trouble seeing what is a pointer and what isn't. Also how does passing a pointer to the map affect the iterator loop ?

Thanks!

Don't write your own function, use the standard library : std::find_if is what you are looking for :

auto it = std::find_if (m1.begin(), m1.end(), TestFunction);
if(it != m1.end())
    ...

The iterator (ite) is a stack variable and and you returns a pointer to a variable in the stack (&ite->second). This is wrong.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM