[英]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 : 不要编写自己的函数,请使用标准库:
std::find_if
是您要查找的内容:
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). 迭代器(ite)是一个堆栈变量,您将返回一个指向堆栈中变量的指针(&ite-> second)。 This is wrong.
错了
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.