从函数返回迭代器

use*_*243 2 c++ stl

我有以下示例:

#include <stdio.h>
#include <map>
#include <conio.h>

typedef std::map<int,int> mi;
typedef std::map<int,int>::iterator mit;

mit myfind(mi mymap)
{
    mit it = mymap.find(1);
    printf("in function: %d\n",it->second);

    return it;
}

void main()
{
    mi a;
    a.insert(std::pair<int,int>(1,2));
    a.insert(std::pair<int,int>(3,4));

    mit it = myfind(a);

    printf("out of function: %d\n",it->second);

    _getch();

}
Run Code Online (Sandbox Code Playgroud)

输出是:

功能:2

功能不足:-17891602

为什么?迭代器是否无效?为什么?提前致谢.

Gre*_*ill 8

你返回的迭代某处指向的本地副本mymap已传递到myfind()(这是释放在函数返回时).尝试:

mit myfind(mi &mymap) { ...
Run Code Online (Sandbox Code Playgroud)

这将传递引用,mymap并且不进行复制.