C++ 双链接列表

C++ 双链接列表,c++,xor,doubly-linked-list,C++,Xor,Doubly Linked List,我正在尝试制作一个内存高效的双链接列表。该列表存储下一个和上一个地址的XOR,但是我在函数XOR中遇到了一个错误。错误是: [Error] cast from 'node*' to 'unsigned int' loses precision [-fpermissive] 我的代码是: #include<bits/stdc++.h> using namespace std; struct node { int data; node *next; }*start,*

我正在尝试制作一个内存高效的双链接列表。该列表存储下一个和上一个地址的XOR,但是我在函数
XOR
中遇到了一个错误。错误是:

[Error] cast from 'node*' to 'unsigned int' loses precision [-fpermissive] 
我的代码是:

#include<bits/stdc++.h>
using namespace std;
struct node
{
    int data;
    node *next;
}*start,*temp;
node* XOR(node *a,node *b)
{
    return (node *)((unsigned int)(a)^(unsigned int)(b));   
}
void push(int data)
{
    node *a=new node;
    a->data=data;
    a->next=XOR(start,NULL);
    if(start!=NULL)
    start->next=XOR(start->next,a);
    start=a;
}
void disp()
{
    temp=start;
    node *prev,*cur;
    while(temp)
    {
        cout<<temp->data<<" ";
        if(temp==start)
        {
            prev=temp;
            temp=temp->next;
        }
        else
        {
            cur=temp;
            temp=XOR(temp->next,prev);
            prev=cur;
        }
    }
}
main()
{
    start=NULL;
    push(1);
    push(2);
    push(3);
    push(4);
    push(5);
    push(6);
    push(7);
    push(8);
}
#包括
使用名称空间std;
结构节点
{
int数据;
节点*下一步;
}*开始,*温度;
节点*XOR(节点*a,节点*b)
{
返回(node*)((unsigned int)(a)^(unsigned int)(b));
}
无效推送(整型数据)
{
node*a=新节点;
a->data=数据;
a->next=XOR(开始,空);
如果(开始!=NULL)
开始->下一步=XOR(开始->下一步,a);
开始=a;
}
void disp()
{
温度=启动;
节点*prev,*cur;
while(临时)
{

couta
unsigned int
不能保证与指针一样大,在许多情况下,指针是64位的,
unsigned int
32位。因此,在这种情况下,高32位被丢弃,指针无效。您需要一个
uintpttr\t
而不是
unsigned int

更正后的代码必须首先:

#include <cstdint>
致:

请看这里,以更好地解释uintptr\t和其他类似类型的工作原理


最后,我要提到的是,在大多数现代机器中,xored链表实际上会比普通的双链表慢,而不是快,因为这种技术使CPU和编译器更难预测您正在做什么并很好地优化,而且这种效果比节省小空间带来的速度提升更大。

您应该使用
uintpttr\u t
\include
中定义

uintpttr\u t
的目的就是能够保持
void*
指针,并在不损失精度的情况下转换回指针

使用

uintpttr_t XOR(节点*a,节点*b)
{
返回重新解释(a)^重新解释(b);
}
在您最终返回到有效指针的
uintpttr\t
之前,我不会将其转换回
node*

我不相信当你将一个不是直接从指针转换到指针的
uintpttr\t
进行转换时会发生什么,这是一个很好的定义。

一些批评:…你真的应该使用通常的标准头。在你的情况下,现在应该是这样。还有main()C隐式int不是C++特性,因此你的main至少应该是<代码> int main()/c>。现在你的错误:你正在编译64位,但是未签名int是32。
return (node *)((unsigned int)(a)^(unsigned int)(b));
return (node *)((uintptr_t)(a)^(uintptr_t)(b));
uintptr_t XOR(node *a,node *b)
{
    return reinterpret_cast<uintptr_t>(a)^reinterpret_cast<uintptr_t>(b);   
}