views:

126

answers:

6

Fairly straightforward question. I have a map that I wish to initialize by calling a function like so:

map<string, int> myMap;

myMap = initMap( &myMap );

map<string, int> initMap( map<string, int> *theMap )
{
    /* do stuff... */

However, the compiler is moaning. What's the solution to this?

EDIT 1:

I'm sorry, but I screwed up. The code was correctly written with *theMap, but when I posted the question, I failed to notice that I had omitted the *. So to answer the comment, the error message I get is:

1>Roman_Numerals.cpp(21): error C2143: syntax error : missing ';' before '<'

which is thrown at

map<char, int> initMap( map<char, int> *numerals );

using VC++ 2010 Express and the same error again when I define the function.

A: 

why not do void initMap(map& theMap), instead of making so many copies of the map?

Chris Card
+7  A: 

It's probably complaining because you're passing the address of the map, but your function accepts the map by value.

You might want something more like this:

void initMap(map<string, int>& theMap)
{
    /* do stuff...*/
}
Fred Larson
Thanks for the answer, but I actually rewrote my code incorrectly. It contained the map<> *theMap, I just left the pointer out in the code I wrote here ><
SoulBeaver
+2  A: 

You should accept a pointer or preferably a reference to the map. You could also return a reference for convenience:

map<string, int>& initMap( map<string, int>& theMap )
...
// Call initMap
map<string, int> my_map;
initMap(my_map);
AraK
+2  A: 

Either do:

map<string, int> myMap;
initMap( myMap );

void initMap( map<string, int>& theMap )
{
    /* do stuff in theMap */
}

or do:

map<string, int> myMap;
myMap = initMap(  );

map<string, int> initMap()
{
    map<string, int> theMap;
    /* do stuff in theMap */
    return theMap;
}

i.e. let the function initialise the map you give it, or take the map the function gives you. You're doing both (without a return statement too!)

I'd go for the first option.

jilles de wit
+1  A: 

&myMap is a pointer to a map object, while the argument theMap is a map object.

Two solutions:

Change myMap = initMap( &myMap ); to myMap = initMap( myMap );.

or

Change map<string, int> initMap( map<string, int> theMap ) to map<string, int> initMap( map<string, int> * theMap ).

metaliving
+2  A: 

The canonical solution is just

std::map<std::string, int> initMap();
// ...
std::map<std::string, int> myMap = initMap();

Why the tricky attempt to use an input parameter for a return value? Performance? Modern compilers don't care. In fact, not constructing an empty map will be slightly faster.

MSalters