如何在 C# 中执行"Pointer to Pointer"?
How to do a "Pointer to Pointer" in C#?
我有一个类似于List的数据结构,但我不能使用任何内置容器(List<>等)。我想保留一个"指针对指针",也就是"尾巴",它指向这个列表的尾部。在c++中应该是这样的:
class MyList {
Node* head;
Node** tail; // tail is just a pointer to the "next" pointer of the end of the list.
MyList() {
head = null;
tail = &head;
}
bool isEmpty() {
return head == null;
}
void add(int val) {
*tail = new Node();
(*tail)->val = val;
tail = &((*tail)->next);
}
}
如何在c#中实现这个?谢谢!
用LinkedList代替List<>…怎么样?
你是对的,c#不能(安全地)实现指针对指针。因此,像你这样可爱的代码是不可能的。这是我能做的最好的了。
public class Node {
public Node next;
public int val;
}
class MyList {
Node head = null;
Node tail = null;
public MyList() { }
bool isEmpty() {
return head == null;
}
void add(int val) {
if (isEmpty())
head = tail = new Node();
else {
tail.next = new Node();
tail = tail.next;
}
tail.val = val;
}
}
不坏,是吗?几乎完全相同的长度,(我认为)更容易理解。
c++中有很多c#没有的强大特性,但根据我的经验,c#是一种效率更高的语言,即使对于像这样的低级代码也是如此。
如果你有其他代码,你认为不会屈服于这种简单的翻译,请发布,我们会看看我们能做什么。
相关文章:
- "No-Const Pointer to Const "调用功能
- 为什么"non-standard syntax; use '&' to create a pointer to member"在 CTOR 中使用线程?
- 'Pointer to member'错误C++
- 如果它被定义为 C++ 类中的成员函数,我得到了"non-standard syntax; use '&' to create a pointer to member"
- C++ 中数组的"expression must have pointer-to-object type"是什么?
- 将派生类对象赋值和访问到基类 "pointer to pointer" C++ 中的对象
- 自 C++17 以来使用 std::launder "validate"非"pointer to object"指针值
- 使用c_str时"Use & to create a pointer to a member"
- Visual Studio 2015:获取"non standard syntax, use '&' to create a pointer to member"错误
- 混淆从"array of int[]"到"pointer to int"的显式衰减?
- 将"pointer-to-member"分配给自身
- 当从此到子类中的新对象时,将显示警告"destination for this 'memcpy' call is a pointer to dynamic class..."
- Pointer to boost::thread
- 将"pointer to pointer"传递给模板函数
- 在 2D 阵列分配期间对 calloc 进行"expression must have (pointer-to) function type"
- 禁用 Clang 中的"cast from pointer to smaller type uint32_t"错误
- 收到"void* is not a pointer-to-object type"错误,但使用 XCode 时代码完美执行
- 将"pointer to a child class"追加到"pointer to the parent class"向量中
- 如何在 c++ 中从 "pointer-to-objects" 向量访问对象
- 在C++,我收到一条消息"error: 'void*' is not a pointer-to-object type"