第一张图是用const char*作key的,第二张则是用std::string作key的。可以看到除去std::unordered_map的构造函数,剩下的基本是hash、operator new这两个函数占时间了。在const char*作key的时,hash函数占了22%,new函数占9.66%,而std::string时,new占了15.42,hash才9.72%,因此这两者的效率没差多少。 看到自己...
首先为什么要用 char*作为std::map中的key map<char*,int>和map<string,int>在插入和存储效率的对比。 插入100000条 查询100000次 map<string,int> 119ms 89ms map<char*,int> 9ms 6ms 声明map时需要添加一个cmp比较函数,不然map在比较时,使用char *的指针进行比较,而不是比较char字符串。 #include <cst...
map_test["a"] = "a"; 编译器自动加入char* -> string的函数,而string重载了==操作符函数,内部的判断不是判断指针是否相等,而是判断字符串是否相等,这样一来,实际上只会有一个"a"插入到map中。 实际上用string的好处还有很多,例如它内部封装好了大部分常用字符串操作函数,更重要的是支持类似如下的方法: st...
std::string是 C++ 标准库中的一个类,它提供了一系列用于处理字符串的方法。它的实现通常依赖于以下特性: 动态数组:std::string通常使用一个动态数组(如char数组)来存储字符。这个数组的大小通常比实际存储的字符数大1,以便在末尾存储空字符'\0',从而与 C 风格字符串兼容。 容量和大小:std::string区分“大小”...
2. 3. 出错的位置都是funcIter++处.有两种情形: 卡死. 崩溃.错误也是很奇怪: #0 0x00007fcf790ff458 in std::less<char*>::operator() ( this=0x7fcf79302420 <g_oRecordFunctionMap>, __x=@0xf8: <error reading variable>, __y=@0x7fcf45199060: 0x7fcf28042400 "tcpclient.c-tcpclient_recv-...
(std::map<std::string, int>::const_iterator it = m.begin(); it != m.end(); ++it)// std::cout << it->first << " = " << it->second << "; ";std::cout<<'\n';}intmain(){// Create a map of three (string, int) pairsstd::map<std::string,int>m{{"CPU",10},{...
#include<iostream>#include<string>#include<vector>#include<map>#include<algorithm>usingnamespacestd;intmain(){ map<char,float> m; m['a'] =3.4; m['b'] =5.3; m['c'] =33.3; m['d'] =43.;autoit = m.find('c'); cout <<"distance : "<< std::distance( it , m.beg...
std::unordered_map<string, int> my_map;my_map["apple"] = 1; 在这个例子中,“apple” 就是键,1 就是值。哈希函数是由unordered_map类自动提供的,我们不需要关心具体的实现。 在口语交流中,我们可以这样描述这个过程:“First, the hash function converts the key to an integer, which is the locatio...
综上所述,虽然可以使用char作为std::map的键,但需要注意比较和内存管理的问题。在实际开发中,建议使用更安全和方便的数据类型作为std::map的键,如std::string。如果确实需要使用char作为键,需要自定义比较函数或比较对象,并确保正确管理内存。 腾讯云相关产品和产品介绍链接地址: ...
适当的std::string赋值习惯用法是使用C++标准库中的std::string类,它是一个具有动态大小的字符串类,可以方便地表示和操作字符串。以下是一些常见的std::string赋值习惯用法: 使用字符串字面量初始化std::string对象:std::string s = "Hello, world!";const char* cstr = "Hello, world!"; std::string s(...