By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
445,798 Members | 1,766 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 445,798 IT Pros & Developers. It's quick & easy.

HOw to pass std::map as parameter?

P: n/a
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
Jul 19 '05 #1
Share this Question
Share on Google+
3 Replies


P: n/a
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

Jul 19 '05 #2

P: n/a
"Woodster" <mi****@127.0.0.1> wrote in message
news:MP************************@news.westnet.com.a u...
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

Jul 19 '05 #3

P: n/a

"Woodster" <mi****@127.0.0.1> wrote in message
news:MP************************@news.westnet.com.a u...
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.
Jul 19 '05 #4

This discussion thread is closed

Replies have been disabled for this discussion.