指向struct 的指针(函数内)

本文介绍了一种算法,该算法接收一个有序数组,并通过递归地选择中间元素作为根节点来构建一个平衡的二叉搜索树。文章详细解释了如何使用迭代器而非指针提高效率,并讨论了在C++中使用new关键字创建动态对象的原因。

/**

  • Definition for a binary tree node.
  • struct TreeNode {
  • int val;
    
  • TreeNode *left;
    
  • TreeNode *right;
    
  • TreeNode(int x) : val(x), left(NULL), right(NULL) {}
    
  • };
    /
    class Solution {
    public:
    typedef vector::iterator pos_t;
    TreeNode
    sortedArrayToBST(pos_t b, pos_t e)
    {
    int n=distance(b,e);
    if(!n) return 0;
    TreeNode* res=new TreeNode(0);
    if (n==1)
    {
    res->val=b;
    return res;
    }
    auto mid=next(b,n/2);
    res->val=mid;
    res->left=sortedArrayToBST(b,mid);
    res->right=sortedArrayToBST(next(mid),e);
    return res;
    }
    TreeNode
    sortedArrayToBST(vector& nums) {
    return sortedArrayToBST(begin(nums), end(nums));
    }
    };
    迭代器的效率要比单纯使用指针要高
    TreeNode
    res=new TreeNode(0);
    此处需要使用new,而不能使用如下代码:
    TreeNode current(0);
    TreeNode *test = &current;
    的原因是,TreeNode current是局部变量,可以作值返回,不能作地址返回,其地址指向的值在析构函数(destructor)中被释放调了,所以调用指针会出错。
    另外,使用new后,最好在析构函数中使用delete将空间释放掉。
### struct作为函数参数的用法 在C和C++中,struct可以作为函数参数传递,主要有以下几种方式: #### 1. 值传递 将struct的副本传递给函数函数内部对参数的修改不会影响原始struct变量。示例代码如下: ```c #include <stdio.h> // 定义一个struct struct Point { int x; int y; }; // 函数接受struct作为值参数 void printPoint(struct Point p) { printf("x: %d, y: %d\n", p.x, p.y); } int main() { struct Point p = {10, 20}; printPoint(p); return 0; } ``` 在上述代码中,`printPoint`函数接受一个`struct Point`类型的参数`p`,它是`main`函数中`p`的副本。 #### 2. 指针传递 传递struct指针函数函数内部可以通过指针修改原始struct变量。示例代码如下: ```c #include <stdio.h> // 定义一个struct struct Point { int x; int y; }; // 函数接受struct指针作为参数 void movePoint(struct Point *p) { p->x += 1; p->y += 1; } int main() { struct Point p = {10, 20}; movePoint(&p); printf("x: %d, y: %d\n", p.x, p.y); return 0; } ``` 在上述代码中,`movePoint`函数接受一个`struct Point`类型的指针`p`,通过指针可以直接修改`main`函数中的`p`。 #### 3. 引用传递(C++特有) 在C++中,可以使用引用传递struct函数内部对引用的修改会影响原始struct变量。示例代码如下: ```cpp #include <iostream> // 定义一个struct struct Point { int x; int y; }; // 函数接受struct引用作为参数 void movePoint(Point &p) { p.x += 1; p.y += 1; } int main() { Point p = {10, 20}; movePoint(p); std::cout << "x: " << p.x << ", y: " << p.y << std::endl; return 0; } ``` 在上述代码中,`movePoint`函数接受一个`Point`类型的引用`p`,对引用的修改会直接影响`main`函数中的`p`。 ### struct作为函数参数的注意事项 - **性能考虑**:值传递会复制整个struct,对于较大的struct,会消耗较多的时间和内存。因此,对于大型struct,建议使用指针或引用传递。 - **内存管理**:使用指针传递时,要确保指针指向有效的内存地址,避免空指针和野指针。 - **初始化问题**:如果struct没有定义构造函数,且所有成员变量全是public的话,可以用大括号初始化。但如果定义了构造函数,就不能用大括号进行初始化了 [^2]。 - **函数内部修改**:使用值传递时,函数内部对参数的修改不会影响原始struct变量;而使用指针或引用传递时,函数内部的修改会影响原始struct变量。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值