c++ pass a map by reference into function

后端 未结 1 995
刺人心
刺人心 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<map> 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<map>
    
    void function2(std::map<int, int> &temp_map); //forward declaration
    
    void function1(){
        std::map<int, int>  my_map; //automatic variable 
                                    //no need to make it pointer!
        function2(my_map); 
    }
    
    void function2(std::map<int, int> &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<int, int> &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)
提交回复
热议问题