Question

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.

Was it helpful?

Solution

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] ) );

OTHER TIPS

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.

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 );
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top