变量超出范围后如何保留向量值?
How vector value is retained after the variable goes out of scope?
>在foo((中将局部变量向量分配给map<int , std::vector<int>> m1
,希望s1的值一旦超出范围就无法访问。但事实并非如此。看起来矢量中的元素存储在堆内存中,局部变量 s1 存储在堆栈中。当 S1 存储在 Map 中时,看起来它分配了一个新的堆内存并将值复制到其中。我的理解是对的吗? 我正在 foo 中打印每个矢量元素的地址以及地图中每个矢量元素的地址。
#include <iostream>
#include <map>
#include <set>
#include<vector>
using namespace std;
std::map<int , std::vector<int>> m1;
void foo(){
vector<int> s1 = { 10, 20, 30, 40 };
cout << "local var address: " << &s1 << "n";
cout << "Element address " << &s1[0] << " " << &s1[1] << " "
<< &s1[3] << " " << &s1[4] << "n";
m1[1] = s1;
}
int main() {
foo();
cout << "nElement value and address in map:n";
for (auto it = m1[1].begin(); it != m1[1].end();it++) {
cout << *it << " " << &m1[1][*it] << "n";
}
return 0;
}
output:
local var address: 0x7fff41714400
Element address 0xc07c20 0xc07c24 0xc07c2c 0xc07c30
Element value and address in map:
10 0xc08cc8
20 0xc08cf0
30 0xc08d18
40 0xc08d40
当你执行m1[1] = s1;
时,你正在调用m1[1]
的赋值运算符。如果点击该链接,则调用第一个实例,cppreference 将其描述为:
1( 复制赋值运算符。将内容替换为其他内容的副本。
(强调我的(
所以你正在查看两个完全不同的向量和两个完全不同的项目集的地址。比较它们是没有意义的。
std::map<int , std::vector<int>>
有std::vector<int>
的value_type
。这意味着存储在地图中的每个项目都包含这样的矢量对象。
它不包含对向量的引用,也不包含对向量的指针,它实际上是一个对象。
这意味着,如果在地图外部创建矢量并将其分配给地图元素,则必须移动或复制该矢量。
相关文章:
- std::向量迭代器和调整大小/保留的奇怪/有趣行为
- C++ STL 向量保留太多容量会消耗大量内存吗?
- 引用保留向量中的第一个元素
- 如何在保留原始索引的同时对向量的向量进行排序
- 如何将两个点的向量保留在一个向量中
- 向量是否知道在由一对迭代器初始化时首先保留?
- 在向量 (C++) 中保留插入元素的地址
- 为什么在保留向量中插入空结构会增加内存
- 保留一个reference_wrapper对象的向量,这是可能的
- 实现定义为使用保留向量而不调整其大小
- 如何保留指向插入到集合中然后推送到向量中的对象的指针
- 分配给尚未调整大小但保留的向量元素,称为合法
- 在构造时保留子向量
- 通过引用函数传递向量,但更改不会保留
- 将 Point 的向量和 int 的向量保留在一个数组的结构中
- 如何保留多维向量
- C++快速排序向量并保留原始索引号
- 关于向量保留大内存的问题
- 用保留向量初始化向量的向量
- 从保留的向量读取比从非保留向量读取更快