gpt4 book ai didi

c++ - 返回后丢失的 std::map 值

转载 作者:行者123 更新时间:2023-11-30 04:19:10 25 4
gpt4 key购买 nike

如何在将映射从一个函数传递到另一个函数时正确处理内存。

我有一个函数可以返回它构建的 map 。值对象是类 foo。我在三个不同的位置打印 foo,它们都给出了不同的值。第一次,它给出了正确的值。第二个和第三个是垃圾。

我知道我必须在正确的位置创建 Foo 对象指针。

我想知道在哪里?

std::map<int,Foo*> function_that_returns_the_map(){

std::map<int,Foo*> myMap;

{

int v = 0;
Foo *b = new Foo();

// PRINTING FOO FIRST

std::cout<<""<<*b<<endl;

myMap.insert(std::pair<int,Foo*>(v,b))

}

// PRINTING FOO AGAIN

for(map<int,Foo*>::iterator it = myMap.begin();
it != myMap.end(); ++it)
{
std::cout << " " << *(it->second) << "\n";
}


return myMap;
}

std::map<int, Foo*> myMap;
myMap = function_that_returns_the_map();

//PRINTING FOO AGAIN.

std::map<int, Board*>::iterator it = myMap.begin();
for (it=myMap.begin(); it!=myMap.end(); ++it)
cout<<" "<<*(it->second)<<endl;

Click here查看我的实际代码。

更新:Foo 的成员变量未使用“new”运算符进行分配。因此,一旦超出范围,它们就会超出范围并具有垃圾值。

最佳答案

您的代码中有很多小错误(我认为这只是拼写错误)。我已经修复了这些问题并提供了一个 Foo 类,它可以正常编译和运行,在所有三个地方打印正确的值:

#include <iostream>
#include <map>

struct Foo
{
Foo() : someValue(5) {};
int someValue;
};

std::map<int,Foo*> function_that_returns_the_map()
{
std::map<int,Foo*> myMap;
{
int v = 0;
Foo *b = new Foo();
std::cout << (*b).someValue << std::endl; // PRINTING FOO FIRST
myMap.insert(std::pair<int,Foo*>(v,b));
}

// PRINTING FOO AGAIN
std::map<int, Foo*>::iterator it = myMap.begin();
for(it; it != myMap.end(); ++it)
{
std::cout << it->second->someValue << "\n";
}
return myMap;
}

int main()
{
std::map<int, Foo*> myMap;
myMap = function_that_returns_the_map();

//PRINTING FOO AGAIN.

std::map<int, Foo*>::iterator it = myMap.begin();
for (it; it!=myMap.end(); ++it)
std::cout << it->second->someValue << std::endl;
return 0;
}

Click here查看输出。

因此,问题一定出在您未在问题中提及的内容中。为了能够提供进一步的帮助,我们需要查看真实的代码。

关于c++ - 返回后丢失的 std::map 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16005533/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com