Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function that returns iterator from a map

I have a class with a map<K,V> variable which gets its value in the c'tor like so:

class Foo {
    map<K,V> m;
    Foo (map<K,V>& newM) : m(newM) {}
    map<K,V>::iterator bar () { ... }
}

the function bar iterates through the map m, and return some an iterator to some element. I'm calling the function like this:

std::map<K,V> map;
//fill map
Foo foo(map);
map<K,V>::iterator it = foo.bar();

my question is, at this moment, does it point to a member of map? or was it copied to Foo.m and therefor the iterator points to a different map?

like image 768
Amir Rachum Avatar asked Dec 15 '25 20:12

Amir Rachum


1 Answers

It will point to the new map, as you copied the map into variable m in the ctor of the class. The statement m(newM) in the initialization list invokes the copy constructor of the std::map class and copies individual elements of the passed map into the destintation map m. Hence when you invoke bar method, it will return the iterator from this new map.

EDIT Example code for storing the std::map as reference:

class Foo {
public:
    map<int,int>& m; //Note: the change here, I am storing a reference
    Foo (map<int,int>& newM) : m(newM) {}
    map<int,int>::iterator bar () { return m.begin();}
};


int main()
{
    std::map<int,int> map1;
    Foo foo(map1);
    map<int,int>::iterator it = foo.bar();

    if(it == map1.begin())
    {
        std::cout<<"Iterators are equal\n";
    }
}
like image 194
Naveen Avatar answered Dec 17 '25 12:12

Naveen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!