views:

522

answers:

3

Hi all,

I have a map like

std::map< int, int> random[50];

How can i pass this map as a parameter to a function say Perform()?

Thanks in advance.

+2  A: 

Assuming that Perform() has some way of knowing the size of random, you could pass a pointer to random... eg:

Perform(&random);

Alternatively, you could use a std::list of std::maps, and pass a pointer (or even a copy) of that list to Perform():

Perform(random); or Perform(&random);

depending on how Perform is declared, of course.

Faxwell Mingleton
You could also pass a reference to that std::list of std::map's.
jgottula
Faxwell Mingleton
Kirill V. Lyadvinsky
Correct - my bad! I guess that means it's time for bed. Well spotted, and sorry if I caused any confusion!
Faxwell Mingleton
+3  A: 
void Perform( std::map< int, int > r[], size_t numElements );

or

void Perform( std::map< int, int >* r, size_t numElements );

Then, either way, call

Perform( random, 50 );

Edit: this can also be called as follows for any const array size.

Perform( random, sizeof( random ) / sizeof ( random[0] ) );
Goz
Thanks! it worked perfectly!
aneesh
+1  A: 

Depending on whether you can make Perform a template function or not, you can choose to

  • pass the map by (const) reference: void Perform( const std::map<int,int> (& map)[50] )
  • pass a pointer and a size (the C way)
  • create a template that automatically deduces the size of the array

This is a code fragment illustrating all three of them.

#include <map>

// number 50 hard coded: bad practice!
void Perform( const std::map<int,int> (& maps ) [50]  ) {}

// C-style array passing: pointer and size
void Perform( const std::map<int,int>* p_maps, size_t numberofmaps ){}

// 'modern' C++: deduce the map size from the argument.
template<size_t N>
void TPerform( const std::map<int,int> (& maps)[N] ) {}



int main() {
    std::map<int,int> m [ 50 ];
    Perform( m );
    Perform( m, 50 );
    TPerform( m );
}
xtofl
I left out the version where the array is passed in by value, assuming that this would cost unnecessary performance.
xtofl
Looks like you included that as the second option "c-style array passing". I dunno of another way to actually copy it when passing. :)
Johannes Schaub - litb
I meant real value-passing, like `Perform( map<int,int> arg[50] )`. Although this may be translated as pointer-passing, indeed.
xtofl