STL容器范围(STL Scope of containers)

编程入门 行业动态 更新时间:2024-10-20 03:13:01
STL容器范围(STL Scope of containers)

我只是想知道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.

更多推荐

本文发布于:2023-08-01 12:10:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1358038.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:容器   STL   containers   Scope

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!