首页 > 解决方案 > 变量超出范围后如何保留向量值?

问题描述

在 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

标签: c++vector

解决方案


当你这样做时m1[1] = s1;,你正在调用m1[1]'s assignment operator。如果您点击该链接,您将调用第一个实例,cppreference 将其描述为:

1) 复制赋值运算符。用其他内容的副本替换内容。

(强调我的)

因此,您正在查看两个完全不同的向量和两组完全不同的项目的地址。比较它们是没有意义的。


推荐阅读