[英]How can I write a function that, given a pointer to a map, returns a pointer to a specific element in the map?
我有一張地圖:
std::map<int,float> m1;
我想將指向該映射的指針傳遞給一個函數,該函數將遍歷該映射並根據某種條件返回指向該映射中特定元素的指針。
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;
}
此代碼未編譯。 我無法看到的是一個指針,什么不是。 另外,將指針傳遞給映射會如何影響迭代器循環?
謝謝!
不要編寫自己的函數,請使用標准庫: std::find_if
是您要查找的內容:
auto it = std::find_if (m1.begin(), m1.end(), TestFunction);
if(it != m1.end())
...
迭代器(ite)是一個堆棧變量,您將返回一個指向堆棧中變量的指針(&ite-> second)。 錯了
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.