c++ - 变量超出范围后如何保留向量值?
问题描述
在 foo() 中给 a 赋值一个局部变量向量map<int , std::vector<int>> m1
,希望 s1 的值一旦超出范围就无法访问。但事实并非如此。看起来向量中的元素存储在堆内存中,而局部变量 s1 存储在堆栈中。当 s1 存储在 map 中时,它看起来像是分配了一个新的堆内存并将值复制到它。我的理解对吗?我正在打印 foo 中每个向量元素的地址以及 map 中每个向量元素的地址。
#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]
's assignment operator。如果您点击该链接,您将调用第一个实例,cppreference 将其描述为:
1) 复制赋值运算符。用其他内容的副本替换内容。
(强调我的)
因此,您正在查看两个完全不同的向量和两组完全不同的项目的地址。比较它们是没有意义的。
推荐阅读
- python - 如何使用python在单个数据框中查找具有多个公共值的列
- django - 如何使用 DjangoORM 从两个表中获取数据?
- python - 应用关闭时不会显示通知
- azure - 将出站 IP 映射到 Azure 应用服务中的 1 个 IP
- bash - Bash:重定向的行为
- java - 将 scala Flatten 转换为在 Spark 中的 Java 中使用
- java - Janusgraph:Cassandra 节俭超时异常
- typescript - 打字稿:在“{}”类型上找不到带有“字符串”类型参数的索引签名
- laravel - 如何解决具有不同列数的 Laravel 联合查询
- c++ - QVariante with double inside - 转换回 double 导致不同的结果