课堂内外,为什么相同的数据具有不同的值?
作为主题,我在两个晚上混淆了这个问题。
我尝试使用函数build_bdds修改地图数据结构的值,但是在函数内部打印的值与函数外部的值不同。
我将struct map_data的bool元素更改为int类型,并遇到了相同的问题。 我怀疑我使用的是错误的指针,但无法弄清楚怎么了。
这是我的代码。
#include <bits/stdc++.h>
using namespace std;
struct map_Data{
bool hi;
bool lo;
};
map<pair<int, int>, map_Data*> outs;
class MWVC{
public:
map_Data build_BDDs(map<pair<int, int>, map_Data*> & ins){
map_Data txt;
txt.hi = 1;
txt.lo = 0;
ins[make_pair(2,4)] = &txt;
cout << ins[make_pair(2,4)]->hi << ";" << ins[make_pair(2,4)]->lo << endl;
return * ins[make_pair(2,4)];
}
};
int main(){
MWVC ojb;
map_Data a;
a.hi = 1;
a.lo = 0;
outs[make_pair(1,2)] = &a;
if(outs[make_pair(1,4)]){
cout << outs[make_pair(1,4)]->hi << endl;
}
map_Data b = ojb.build_BDDs(outs);
cout << outs[make_pair(2,4)]->hi << ";" << outs[make_pair(2,4)]->lo << ";" << b.hi << ";" << b.lo << endl;
return 0;
}
结果是
1;0
0;0;1;0
感谢进步。
As the topic, I was confusing this question for two night.
I tried to use function build_BDDs to modify the value of map data structure outs, but the value printed inside the function is not the same as outside the function.
I changed the bool elements of struct map_Data to int type and had the same problem.
I suspect I'm using the wrong pointer, but can't figure out what's wrong.
here is my codes.
#include <bits/stdc++.h>
using namespace std;
struct map_Data{
bool hi;
bool lo;
};
map<pair<int, int>, map_Data*> outs;
class MWVC{
public:
map_Data build_BDDs(map<pair<int, int>, map_Data*> & ins){
map_Data txt;
txt.hi = 1;
txt.lo = 0;
ins[make_pair(2,4)] = &txt;
cout << ins[make_pair(2,4)]->hi << ";" << ins[make_pair(2,4)]->lo << endl;
return * ins[make_pair(2,4)];
}
};
int main(){
MWVC ojb;
map_Data a;
a.hi = 1;
a.lo = 0;
outs[make_pair(1,2)] = &a;
if(outs[make_pair(1,4)]){
cout << outs[make_pair(1,4)]->hi << endl;
}
map_Data b = ojb.build_BDDs(outs);
cout << outs[make_pair(2,4)]->hi << ";" << outs[make_pair(2,4)]->lo << ";" << b.hi << ";" << b.lo << endl;
return 0;
}
and the result is
1;0
0;0;1;0
Thanks advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您
build_bdds
函数存储地图中的本地变量的地址。当功能返回时,它指向的内存可以随时覆盖。对于此情况,只需放下指针,让STD :: MAP担心内存管理:
并将build_bdds更改为:
You
build_BDDs
function stores the address of a local variable in the map. When the function returns, the memory it points to can be overwritten at any time.For this instance, just drop the pointers and let the std::map worry about memory management:
and change build_BDDs to: