我只是想知道STL容器的范围。
例如。 //有一个创建unordered_map的函数,并传递给set_map来填充其中的值。
int foo() { unorderd_map<char,int>mymap; set_map(mymap); } set_map (unorderd_map<char,int> mmap){ //...setting values of map }在这种情况下,foo中mymap的范围仅限于函数foo(),或者mymap是通过引用set_map()传递的,并且set_map中所做的任何更改都将反映到foo()中的mymap中?
我还想知道仍然将容器作为函数参数传递,即它们是通过值传递还是通过引用传递。
谢谢
I just wanted to know of the scope of the STL containers.
For eg. //Have a function which creates an unordered_map and passes to set_map to fill values in it.
int foo() { unorderd_map<char,int>mymap; set_map(mymap); } set_map (unorderd_map<char,int> mmap){ //...setting values of map }In this case will the scope of mymap in foo be limited to the function foo() only or mymap is passed by reference to set_map() and whatever changes done in set_map will be reflected to mymap in foo() ?
I also wanted to know how are still containers passed as function parameters, i.e. are they passed by value or they are passed by reference.
Thank You
最满意答案
mymap 作为副本传递给set_map ,因此set_map只能看到自己的地图副本,而不是原始的mymap 。 在set_map所做的set_map将仅应用于副本,并且不会影响原始mymap 。
要通过引用传递地图,您需要明确声明它:
set_map (unordered_map<char,int>& mmap) // ^ will be passed by reference now.现在, set_map的更改将更改作为参数传递的原始对象。
mymap is passed as a copy to set_map, so set_map only sees its own copy of the map, not the original mymap. Changes made in set_map will be only applied to the copy, and will not affect the original mymap.
To pass the map by reference you need to declare it explicitly:
set_map (unordered_map<char,int>& mmap) // ^ will be passed by reference now.Now the changes in set_map will alter the original object that was passed as the parameter.
更多推荐
发布评论