HOw to pass std::map as parameter?

W

Woodster

I have declared the following

std::map<std::string, std::string> myMap;

to pass myMap to functions should I be declaring functions as:

void function(std::map<std::string, std::string>);

or is there a preferred/better method of doing this?

Thanks in advance

Sean Hannan
 
M

Marco Wahl

Hi Sean!
I have declared the following

std::map<std::string, std::string> myMap;

to pass myMap to functions should I be declaring functions as:

void function(std::map<std::string, std::string>);

or is there a preferred/better method of doing this?
Yes.
void function(const std::map<std::string, std::string>&);
This avoids the copy of the map which could be heavy work.

Ciao, Marco
 
D

David White

Woodster said:
I have declared the following

std::map<std::string, std::string> myMap;

to pass myMap to functions should I be declaring functions as:

void function(std::map<std::string, std::string>);

or is there a preferred/better method of doing this?

It depends on what the function does.

Unless you need to copy the whole map when you pass it, a reference to it
would be better:
void function(std::map<std::string, std::string> &);

And if you aren't changing the map in the function, use a const reference:
void function(const std::map<std::string, std::string> &);

You can also use a typedef if you want:
typedef std::map<std::string, std::string> MyMap;

Then use MyMap everywhere you would have used std::map<std::string,
std::string>, e.g.,
void function(const MyMap &);

DW
 
J

jeffc

Woodster said:
I have declared the following

std::map<std::string, std::string> myMap;

to pass myMap to functions should I be declaring functions as:

void function(std::map<std::string, std::string>);

or is there a preferred/better method of doing this?

In addition to the "pass by reference" suggestion, I usually make a typedef
for something like that - something that makes it a more meaningful type
name, which also has the advantage of making the function list easier to
read. It does add a slight layer of abstraction though - when you use the
function, you have to go look up that typedef first to see what it really
means.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top