STL映射的奇怪输出

strange output of STL map

本文关键字:输出 映射 STL      更新时间:2023-10-16

C程序员试图调用C++映射(使用关联数组或哈希的功能)。

该字符串只是一个开始,将继续散列二进制字符串。第一步就被卡住了。想知道为什么这个程序的输出只会返回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){
    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 %dn", sizeof(Employees));
   set(Employees, "jin", 100);
   set(Employees, "joe", 101);
   set(Employees, "john", 102);
   set(Employees, "jerry", 103);
   set(Employees, "jobs", 1004);
    printf("value %dn", get(Employees, "joe"));
}

谢谢。

发现了两个错误:

printf("size is %dn", sizeof(Employees));

必须是

printf("size is %dn", Employees.size());

sizeof提供的是对象的大小,而不是其中的元素数。


int set(map<string, int> e, char* s, int value) 

必须是

int set(map<string, int> &e, char* s, int value)

否则,你会给函数一个副本,而不是原来的(如C)。离开函数范围后,副本将被丢弃。原件没有改动。