memcmp用法&&实现

memcmp用法&&实现 

目录

memcmp用法&&实现 

用法:

实现 :

strcmp &&  memcmp区别


  • 用法:

头文件:<memory.h>或 <string.h>

函数功能:比较内存区域buf1和buf2的前count个字节。该函数是按字节比较的

函数返回值:

        当buf1<buf2时,返回值<0
        当buf1=buf2时,返回值=0
        当buf1>buf2时,返回值>0

函数原型:

int memcmp(const void *str1, const void *str2, size_t n)
  • 实现 :

int My_memcmp(const void *dest,const void *src,size_t n)
    {
        assert(dest!=NULL && src!=NULL && n>0);
        const char *pdest=(char*)dest;
        const char *psrc=(char*)src;
        while(*pdest == *psrc && --n>0)
        {
            pdest++;
            psrc++;
        }
        int a=*pdest-*pstc;
        if(a>0){return 1;}
        else if(a<0){return -1;}
        else{return 0;}
        return a;
        
    }

strcmp &&  memcmp区别 

strcmp比较的字符串,而memcmp比较的是内存块,strcmp需要时刻检查是否遇到了字符串结束的 /0 字符,而memcmp则完全不用担心这个问题,所以memcmp的效率要高于strcmp。


 


 

 

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
好,下面是使用广度优先搜索算法实现八数码问题的 C++ 代码: ```c++ #include <bits/stdc++.h> using namespace std; const int N = 3; // 8数码问题的规模为3 const int dx[] = {0, 0, 1, -1}; // 四个方向的x坐标变化 const int dy[] = {1, -1, 0, 0}; // 四个方向的y坐标变化 struct Node { int state[N][N]; // 当前状态 int x, y; // 空格的位置 int step; // 当前步数 Node() {} Node(int s[][N], int _x, int _y, int _step) { memcpy(state, s, sizeof(state)); x = _x, y = _y, step = _step; } }; int st[N][N]; // 初始状态 int ed[N][N]; // 目标状态 int bfs() { queue<Node> q; unordered_set<string> vis; // 判重 q.push(Node(st, 0, 0, 0)); vis.insert(string((char*)st, (char*)st + N * N)); // 将初始状态加入到visit中 while (q.size()) { auto t = q.front(); q.pop(); if (!memcmp(t.state, ed, sizeof(ed))) return t.step; // 判断是否到达目标状态 for (int i = 0; i < 4; i ++ ) { int a = t.x + dx[i], b = t.y + dy[i]; if (a < 0 || a >= N || b < 0 || b >= N) continue; // 判断是否越界 auto c = t.state; swap(c[t.x][t.y], c[a][b]); // 交换空格和相邻位置的数 if (vis.count(string((char*)c, (char*)c + N * N))) continue; // 判断是否重复 q.push(Node(c, a, b, t.step + 1)); // 将新状态加入队列 } } return -1; } int main() { for (int i = 0; i < N; i ++ ) for (int j = 0; j < N; j ++ ) cin >> st[i][j]; for (int i = 0; i < N; i ++ ) for (int j = 0; j < N; j ++ ) cin >> ed[i][j]; cout << bfs() << endl; return 0; } ``` 在该代码中,我们定义了一个 `Node` 结构体,表示当前状态,包含当前状态的数组 `state`,空格的位置 `x` 和 `y`,以及当前的步数 `step`。`bfs` 函数中使用队列进行广度优先搜索,搜索过程中使用哈希表进行判重。在搜索过程中,我们在四个方向上进行移动,并判断是否越界、是否重复,如果满足条件,我们将新状态加入队列。最终,如果到达目标状态,我们返回当前步数,否则返回 -1。 注意:上述代码只是给出了一种实现方法,实际上八数码问题还有其他解法和优化。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值