简体   繁体   English

从函数返回迭代器

[英]returning an iterator from a function

I have the following example: 我有以下示例:

#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();

}

The output is: 输出是:

in function: 2 功能:2

out of function: -17891602 功能不足:-17891602

Why? 为什么? Does the iterator become invalid? 迭代器是否无效? Why? 为什么? Thanks in advance. 提前致谢。

Your returned iterator is pointing somewhere into the local copy of mymap that was passed into myfind() (which is deallocated when the function returns). 你返回的迭代器指向某个地方的mymap的本地副本,该副本被传递给myfind() (当函数返回时被释放)。 Try: 尝试:

mit myfind(mi &mymap) { ...

This will pass a reference to mymap and no copy is made. 这将传递对mymap引用 ,并且不会进行任何复制。

You're passing the map by value. 您按值传递地图。 Therefore, myfind() operates on a copy of the map, and the iterator is only valid for the copy. 因此,myfind()对映射的副本进行操作,迭代器仅对副本有效。 Pass the map by reference instead. 通过引用传递地图。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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