2

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

out of function: -17891602

Why? Does the iterator become invalid? Why? Thanks in advance.

sbi
  • 219,715
  • 46
  • 258
  • 445
user581243
  • 167
  • 2
  • 8

2 Answers2

8

Your returned iterator is pointing somewhere into the local copy of mymap that was passed into myfind() (which is deallocated when the function returns). Try:

mit myfind(mi &mymap) { ...

This will pass a reference to mymap and no copy is made.

Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
  • @user: You might want to read on [How to pass objects to functions in C++?](http://stackoverflow.com/questions/2139224/how-to-pass-objects-to-functions-in-c/2139254#2139254). – sbi Jan 19 '11 at 10:38
1

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. Pass the map by reference instead.

tbleher
  • 1,077
  • 1
  • 9
  • 17