STL映射的奇怪输出 < P>程序员试图调用C++映射来使用相关数组或哈希函数。
字符串只是一个开始,将继续哈希二进制字符串。第一步就卡住了。不知道为什么这个程序的输出只返回0STL映射的奇怪输出 < P>程序员试图调用C++映射来使用相关数组或哈希函数。,c++,stl,C++,Stl,字符串只是一个开始,将继续哈希二进制字符串。第一步就卡住了。不知道为什么这个程序的输出只返回0 #include <string.h> #include <iostream> #include <map> #include <utility> #include <stdio.h> using namespace std; extern "C" { int get(map<string, int> e, char* s){
#include <string.h>
#include <iostream>
#include <map>
#include <utility>
#include <stdio.h>
using namespace std;
extern "C" {
int get(map<string, int> e, char* s){
return e[s];
}
int set(map<string, int> e, char* s, int value) {
e[s] = value;
}
}
int main()
{
map<string, int> Employees;
printf("size is %d\n", sizeof(Employees));
set(Employees, "jin", 100);
set(Employees, "joe", 101);
set(Employees, "john", 102);
set(Employees, "jerry", 103);
set(Employees, "jobs", 1004);
printf("value %d\n", get(Employees, "joe"));
}
谢谢。发现了两个bug:
printf("size is %d\n", sizeof(Employees));
一定是
printf("size is %d\n", Employees.size());
int set(map<string, int> &e, char* s, int value)
sizeof提供对象的大小,而不是其中的元素数
一定是
printf("size is %d\n", Employees.size());
int set(map<string, int> &e, char* s, int value)
否则,您将为函数提供一个副本,而不是C中的原始副本。离开函数范围后,副本将被丢弃。原始地图不会更改。因为您按值传递地图。尝试int setmap&e,char*s,int value和getmap&e,char*s,并使用std::string代替char*…printfsize为%d\n,sizeofEmployees;可能不会给你你期待的价值,谢谢大家,还得习惯于C++:-是的。我之所以选择SizeOffemployees,是因为我想知道传递对象时的开销。谢谢