当前位置:网站首页>C language hashtable/hashset library summary
C language hashtable/hashset library summary
2022-07-03 03:39:00 【___ Bozi mi pro】
stay https://stackoverflow.com/questions/1138742/looking-for-a-good-hash-table-implementation-in-c Many related libraries are introduced in . After personal screening , Comprehensively consider the execution efficiency 、 The perfection of the document 、 The supported data types are in three aspects , I chose uthash.
Official documents can be found in :http://troydhanson.github.io/uthash/userguide.html
* If you want to be HashSet use , It only needs value Just assign any value
* If you only need String Type of key and value, You can also consider strmap
* There's no choice python Built in libcfu( Download address , Official documents ), Because it's in Android There are many problems when compiling on the environment of .
Brief example ( See official documents for details )
1. initialization
#include "uthash.h"
struct my_struct {
int id; // key
char name[10]; //value
UT_hash_handle hh; // There has to be , Let this structure hashable
};
struct my_struct *users = NULL; // important , Must be initialized to NULL
2. add to
void add_user(int user_id, char *name) {
struct my_struct *s;
HASH_FIND_INT(users, &user_id, s);
if (s == NULL) {
s = (struct my_struct *)malloc(sizeof *s);
s->id = user_id;
HASH_ADD_INT(users, id, s); // id: key Name
}
strcpy(s->name, name);
}
3. lookup
struct my_struct *find_user(int user_id) {
struct my_struct *s;
HASH_FIND_INT(users, &user_id, s);
return s;
}
4. Delete
void delete_user(struct my_struct *user) {
HASH_DEL(users, user);
free(user); // Optional
}
Refer to the official website demo Source code
#include <stdio.h> /* printf */
#include <stdlib.h> /* atoi, malloc */
#include <string.h> /* strcpy */
#include "uthash.h"
struct my_struct {
int id; /* key */
char name[21];
UT_hash_handle hh; /* makes this structure hashable */
};
struct my_struct *users = NULL;
void add_user(int user_id, const char *name)
{
struct my_struct *s;
HASH_FIND_INT(users, &user_id, s); /* id already in the hash? */
if (s == NULL) {
s = (struct my_struct*)malloc(sizeof *s);
s->id = user_id;
HASH_ADD_INT(users, id, s); /* id is the key field */
}
strcpy(s->name, name);
}
struct my_struct *find_user(int user_id)
{
struct my_struct *s;
HASH_FIND_INT(users, &user_id, s); /* s: output pointer */
return s;
}
void delete_user(struct my_struct *user)
{
HASH_DEL(users, user); /* user: pointer to deletee */
free(user);
}
void delete_all()
{
struct my_struct *current_user;
struct my_struct *tmp;
HASH_ITER(hh, users, current_user, tmp) {
HASH_DEL(users, current_user); /* delete it (users advances to next) */
free(current_user); /* free it */
}
}
void print_users()
{
struct my_struct *s;
for (s = users; s != NULL; s = (struct my_struct*)(s->hh.next)) {
printf("user id %d: name %s\n", s->id, s->name);
}
}
int by_name(const struct my_struct *a, const struct my_struct *b)
{
return strcmp(a->name, b->name);
}
int by_id(const struct my_struct *a, const struct my_struct *b)
{
return (a->id - b->id);
}
const char *getl(const char *prompt)
{
static char buf[21];
char *p;
printf("%s? ", prompt); fflush(stdout);
p = fgets(buf, sizeof(buf), stdin);
if (p == NULL || (p = strchr(buf, '\n')) == NULL) {
puts("Invalid input!");
exit(EXIT_FAILURE);
}
*p = '\0';
return buf;
}
int main()
{
int id = 1;
int running = 1;
struct my_struct *s;
int temp;
while (running) {
printf(" 1. add user\n");
printf(" 2. add or rename user by id\n");
printf(" 3. find user\n");
printf(" 4. delete user\n");
printf(" 5. delete all users\n");
printf(" 6. sort items by name\n");
printf(" 7. sort items by id\n");
printf(" 8. print users\n");
printf(" 9. count users\n");
printf("10. quit\n");
switch (atoi(getl("Command"))) {
case 1:
add_user(id++, getl("Name (20 char max)"));
break;
case 2:
temp = atoi(getl("ID"));
add_user(temp, getl("Name (20 char max)"));
break;
case 3:
s = find_user(atoi(getl("ID to find")));
printf("user: %s\n", s ? s->name : "unknown");
break;
case 4:
s = find_user(atoi(getl("ID to delete")));
if (s) {
delete_user(s);
} else {
printf("id unknown\n");
}
break;
case 5:
delete_all();
break;
case 6:
HASH_SORT(users, by_name);
break;
case 7:
HASH_SORT(users, by_id);
break;
case 8:
print_users();
break;
case 9:
temp = HASH_COUNT(users);
printf("there are %d users\n", temp);
break;
case 10:
running = 0;
break;
}
}
delete_all(); /* free any structures */
return 0;
}matters needing attention
- If in Android/gcc Compile times
fall-through between switch labels, You can use pragma The sentence put uthash The relevant code is enclosed
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wimplicit-fallthrough"
// uthash Related codes
#pragma GCC diagnostic pop
Actually, it can be used __attribute__ ((fallthrough)); But the actual measurement did not pragma This method is good .
If compiling times
padding struct 'struct UT_hash_table' with 4 bytes to align 'tail', May, in accordance with the https://github.com/troydhanson/uthash/issues/118#issue-223582662 Answer , adjustment uthash.h The order of variables inIf you want to be HashSet use , You may also need to declare an additional variable , Otherwise, there may be padding The problem of , newspaper
padding struct 'struct fd_struct' with 4 bytes to align 'hh', as follows :
struct fd_struct {
int fd; // key
int padding; // For filling , Or is it char padding[10] And so on. ;
UT_hash_handle hh;
};边栏推荐
- float与0比较
- Recursive use and multi-dimensional array object to one-dimensional array object
- 900w+ data, from 17s to 300ms, how to operate
- Advanced redis applications [password protection, data persistence, master-slave synchronization, sentinel mode, transactions] [not completed yet (semi-finished products)]
- redis高级应用【密码防护、数据持久化、主从同步、哨兵模式、事务】【暂未完成(半成品)】
- npm : 无法将“npm”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。请检查名称的拼写,如果包括路径,请确保路径正确,然后再试一次。
- 用Three.js做一个简单的3D场景
- 解决高並發下System.currentTimeMillis卡頓
- PHP generates PDF tcpdf
- 监听对象中值变化及访问
猜你喜欢
![Learning notes of C programming [compiled by Mr. Tan Haoqiang] (Chapter III sequence programming) 04 C sentence](/img/60/bae0e8d92a53bcd2b2de3fb22b3b99.jpg)
Learning notes of C programming [compiled by Mr. Tan Haoqiang] (Chapter III sequence programming) 04 C sentence

Numpy warning visibledeprecationwarning: creating an ndarray from ragged needed sequences

Vs 2019 installation and configuration opencv

IPv6过渡技术-6to4手工隧道配置实验--尚文网络奎哥

js中#号的作用

Pytorch轻量级可视化工具wandb(local)

Tidal characteristics of the Bohai Sea and the Yellow Sea

Recursion: depth first search

机械臂速成小指南(八):运动学建模(标准DH法)

渤、黄海的潮汐特征
随机推荐
【AI实战】应用xgboost.XGBRegressor搭建空气质量预测模型(一)
Pat class B common function Usage Summary
没有sXid,suid&sgid将进入险境!-尚文网络xUP楠哥
Hi3536c v100r001c02spc040 cross compiler installation
Stop using system Currenttimemillis() takes too long to count. It's too low. Stopwatch is easy to use!
C # webrequest post mode, based on "basic auth" password authentication mode, uploads files and submits other data using multipart / form data mode
Recursion: depth first search
Shardingsphere dynamic data source
File rename
Numpy warning visibledeprecationwarning: creating an ndarray from ragged needed sequences
Introduction à mongodb
IPv6过渡技术-6to4手工隧道配置实验--尚文网络奎哥
MongoDB主配置文件
Null and undefined
Using jasmine to monitor constructors - spying on a constructor using Jasmine
ffmpeg之 一张/多张图片合成视频
Section 26 detailed explanation and demonstration of IPSec virtual private network configuration experiment - simulation experiment based on packettracer8.0
TCP/IP模型中的重磅嘉宾TCP--尚文网络奎哥
MongoDB复制集【主从复制】
Elsevier latex submitted the article pdftex def Error: File `thumbnails/cas-email. jpeg‘ not found: using draf