Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.c++ > #12040

Re: Returning map from map of maps without any copy

From Ian Collins <ian-news@hotmail.com>
Newsgroups comp.lang.c++
Subject Re: Returning map from map of maps without any copy
Date 2011-12-03 20:36 +1300
Message-ID <9ju1sjF570U3@mid.individual.net> (permalink)
References <jbchsm$kac$1@dont-email.me>

Show all headers | View raw


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

Back to comp.lang.c++ | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread


Thread

Returning map from map of maps without any copy ittium <ittium@gmail.com> - 2011-12-03 12:38 +0530
  Re: Returning map from map of maps without any copy Ian Collins <ian-news@hotmail.com> - 2011-12-03 20:36 +1300
  Re: Returning map from map of maps without any copy Jorgen Grahn <grahn+nntp@snipabacken.se> - 2011-12-03 09:27 +0000
  Re: Returning map from map of maps without any copy Goran <goran.pusic@gmail.com> - 2011-12-03 02:05 -0800
  Re: Returning map from map of maps without any copy ittium <ittium@gmail.com> - 2011-12-08 11:29 +0530

csiph-web