c++ pass a map by reference into function

后端 未结 1 996
刺人心
刺人心 2021-02-05 09:20

How can I pass a map by reference into a function? Visual Studio 2010 is giving me an unresolved externals error. Currently, I have the fo

1条回答
  •  甜味超标
    2021-02-05 09:57

    Two things:

    • Add #include at the top, and use std::map instead of just map.
    • Define function2 above function1 Or at least declare function2 above function1.

    Here is how both should be done:

    #include
    
    void function2(std::map &temp_map); //forward declaration
    
    void function1(){
        std::map  my_map; //automatic variable 
                                    //no need to make it pointer!
        function2(my_map); 
    }
    
    void function2(std::map &temp_map){
        //do stuff with the map
    }
    

    Also note that avoid new as much as possible. Use automatic variables by default, unless you've very strong reason not to use it.

    Automatic variables are fast, and the code looks neat and clean. With them it is easier to write exception-safe code.

    EDIT:

    Now as you posted the error, you also realized that,

    I forgot to add the Class that the function was part of to the beginning of it. as in: Player::function2(std::map &temp_map){}

    , as you said in the comment.

    Good that you figured it out yourself. But still, always post the error in your very first post, when you ask the question. Remember this.

    0 讨论(0)
提交回复
热议问题