zoukankan      html  css  js  c++  java
  • 用异或操作实现的交换函数用以实现数组逆置中须要注意的问题

    用元素交换函数实现数组逆置非常easy,如以下代码:(数组左右元素交换)

    #include<iostream>
    #include<stdlib.h>
    using namespace std;
    
    void swap(int &a, int &b)
    {
    	int tmp = a;
    	a = b;
    	b = tmp;
    }
    
    int main()
    {
    	int a[5] = { 1, 2, 3, 4, 5 };
    	int lenth = sizeof(a) / sizeof(a[0]);
    	int head = 0;
    	int tail = lenth - 1;
    
    	while (head <= tail)
    	{
    		swap(a[head], a[tail]);
    		head++;
    		tail--;
    	}
    	for (int i = 0; i < lenth; ++i)
    	{
    		cout << a[i] << endl;
    	}
    	system("pause");
    }


    有人会说。用异或操作实现交换函数效率更高,于是写下例如以下代码:

    <span style="font-family:KaiTi_GB2312;">#include<iostream>
    #include<stdlib.h>
    using namespace std;
    
    void swap(int &a, int &b)
    {
    	a = a ^ b;
    	b = a ^ b;
    	a = a ^ b;
    }
    
    int main()
    {
    	int a[5] = { 1, 2, 3, 4, 5 };
    	int lenth = sizeof(a) / sizeof(a[0]);
    	int head = 0;
    	int tail = lenth - 1;
    
    	while (head <= tail)
    	{
    		swap(a[head], a[tail]);
    		head++;
    		tail--;
    	}
    	for (int i = 0; i < lenth; ++i)
    	{
    		cout << a[i] << endl;
    	}
    	system("pause");
    }</span>

    一执行。结果大跌眼镜:0哪来的????



    异或操作实现交换的机制: a ^ a = 0即同一个元素相异或之后为0

    a =  a ^ b;

    b =  a ^ b = a ^ b ^ b = a;

    a =  a ^ b = a ^ b ^ a = b;


    经分析:原来如此,当head = tail = (lenth-1)/ 2时,二者指向同一个元素,即

    a = b = 3(同一块内存)

    a = a ^ b = 3 ^ 3 = 0(内存内容改变为0)---->>> a = b = 0;

    b = a ^ b = 0 ^ 0 = 0

    a = a ^ b = 0 ^ 0 = 0

    所以运行之后变为了0

    那么该如何改动呢???

    while (head < tail)//改变此处
    	{
    		swap(a[head], a[tail]);
    		head++;
    		tail--;
    	}



    以后注意。把条件写成 while(head < tail)即同一个元素无需交换,即加快了运行效率。又能够避免上述问题!!

    与其相关的一道面试题点击打开链接





  • 相关阅读:
    Gitlab + Gitlab runner + Window powershell
    python 连接SAP 代码
    【翻译】 For OData For C# play on RESTier
    SAP -熟练使用T-Code SHD0
    SAP MM- BAPI_PO_CHANGE 更新PO version 信息(version management)
    SAP PP- OPK8生产订单打印 配置Smart form.
    SAP Smart Form 无法通过程序自定义默认打印机问题解决
    SAP APO-主数据设置
    SAP APO-PP / DS
    SAP APO-供需匹配
  • 原文地址:https://www.cnblogs.com/mthoutai/p/6915562.html
Copyright © 2011-2022 走看看