且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

c ++通过引用将映射传递给函数

更新时间:2023-11-08 23:27:52

两件事:


  • 在顶部添加#include< map> 并使用 std :: map 而不是 map

  • code> function2 上面 function1 或至少声明 function2 $ c> function1 。

  • 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
}

还要注意尽可能避免 new 默认情况下使用自动变量,除非你有很强的理由不使用它。

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.

编辑:

,你也意识到,


我忘了添加该函数是其开头的一部分的类。如:Player :: function2(std :: map & temp_map){}

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){}

在评论中。

很好,你自己想出来了。但仍然,总是在你的第一篇文章,当你提出问题时发布错误。记住这一点。

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.