【问题标题】:Doubly link list双向链表
【发布时间】:2015-10-12 02:54:04
【问题描述】:

我正在尝试制作一个内存高效的双向链表。该列表存储了下一个和上一个地址的 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);
}

【问题讨论】:

  • 一些批评:...你真的应该使用通常的标准头文件。在你的情况下,现在是 。 main() 也是 C。隐式 int 不是 C++ 功能,因此您的 main 至少应该是 int main()。现在您的错误:您正在编译 64 位,但 unsigned int 为 32。使其可移植包括 并使用 std::uintptr_t.
  • 另请参阅:question 1question 2question 3

标签: c++ xor doubly-linked-list


【解决方案1】:

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

修正后的代码必须先:

#include <cstdint>

在顶部某处添加uintptr_t 的声明以及其他各种有用的类型,然后更改行:

return (node *)((unsigned int)(a)^(unsigned int)(b));

收件人:

return (node *)((uintptr_t)(a)^(uintptr_t)(b));

请查看此处以更好地解释 uintptr_t 和其他类似类型的工作原理http://www.cplusplus.com/reference/cstdint/

最后我要提一下,在大多数现代机器中,异或链表实际上会比正常的双向链表更慢,而不是更快,因为该技术使 CPU 和编译器更难预测你在做什么和优化而且这种效果比小空间节省带来的速度提升更大。

【讨论】:

    【解决方案2】:

    您应该使用在#include &lt;cstdint&gt; 中定义的uintptr_t

    uintptr_t 的真正目的是能够持有 void* 指针并在不损失精度的情况下转换回来。

    使用

    uintptr_t XOR(node *a,node *b)
    {
        return reinterpret_cast<uintptr_t>(a)^reinterpret_cast<uintptr_t>(b);   
    }
    

    在您最终返回到作为有效指针的uintptr_t 之前,我不会再将其转换回node*

    我不相信当你投射 uintptr_t 而不是直接从指针转换为指针时会发生什么。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-11-15
      • 2019-06-03
      • 2015-03-24
      • 2015-04-04
      • 2021-11-18
      • 2012-06-25
      • 2015-12-11
      相关资源
      最近更新 更多