将int *添加到指针数组

时间:2018-11-14 10:28:58

标签: c++ pointers

在处理指针的细微差别时遇到很多麻烦。我正在尝试将对整数的引用添加到int指针数组中,但我似乎不太正确。这是我的代码:

int main()
{
    ATree<int> testTree;
    int nums[12] = {5,4,3,7,6,1,2,12,15,9,8,11};
    int *ptr;
    int num, a;
    for (int i = 0; i < 5; ++i)
    {
        a = nums[i];
        *ptr = a;
        testTree.add(nums[i]);
    }
    cout << "Enter a value to search for" << endl;
    cin >> num;
    cout << testTree.search(num) << endl;
    return 0;
}

ATree.h

template <typename Item>
class ATree
{
    public:
    ATree();
    void add(Item);
    void add_helper(int, Item);
    int search(Item);
    int search_helper(int, Item);
    int get_size();
    private:
    int size;
    Item* tree[40];
};
#include "ATree.hpp"

ATree.hpp

template <typename Item>
ATree<Item>::ATree()
{
for (int i = 0; i < 40; ++i)
{ tree[i] = nullptr }
size = 0;
}
template <typename Item>
void ATree<Item>::add(Item obj)
{
    int n = 1;
    if ((tree[1]) == nullptr)
    {
        tree[1] = &obj;
    }
    else
    {
         add_helper(n, obj);
    }
}
template <typename Item>
void ATree<Item>::add_helper(int n, Item obj)
{       
    if (tree[n] == nullptr)
    {
        tree[n] = &obj;
    }
    else if (&obj > tree[n])
    {
        n = 2*n+1;
        add_helper(n, obj);
    }
    else
    {
        n = 2*n;
        add_helper(n, obj);
        }
    }
template <typename Item>
int ATree<Item>::search(Item obj)
{
    int n = 1;
    if (&obj == tree[1])
        { return 1; }
    else
        { return search_helper(n, obj);}
    }
template <typename Item>
int ATree<Item>::search_helper(int n, Item obj)
    {
    if (&obj == tree[n])
        { return n; }
    else if (&obj > tree[n])
    {
        n = 2*n+1;
        return search_helper(n, obj);
    }
    else
    {
        n = 2*n;
        return search_helper(n, obj);
    }
}
template <typename Item>
int ATree<Item>::get_size()
{return size;}

从概念上讲,我发现指针相对简单,但是一旦它们开始在类或数组之间传递(看来数组对它们的处理方式有所不同?),它开始变得与我的直觉相反。

1 个答案:

答案 0 :(得分:2)

基本上存储对象,而不是指针:

LogStash

然后在比较中,比较对象,而不是它们的指针:

Item tree[40];

此代码未经测试,因此无法正常工作,因为您必须添加一个计数器来检查您实际存储了多少个元素(我建议使用template <typename Item> void ATree<Item>::add(Item obj) { int n = 1; if ((tree[1]) == nullptr) // USe a counter here instead, to know how many objects are stored { tree[1] = obj; } else { add_helper(n, obj); } } template <typename Item> void ATree<Item>::add_helper(int n, Item obj) { if (tree[n] == nullptr) { tree[n] = obj; } else if (obj > tree[n]) { n = 2*n+1; add_helper(n, obj); } else { n = 2*n; add_helper(n, obj); } } template <typename Item> int ATree<Item>::search(Item obj) { int n = 1; if (obj == tree[1]) { return 1; } else { return search_helper(n, obj);} } } template <typename Item> int ATree<Item>::search_helper(int n, Item obj) { if (obj == tree[n]) { return n; } else if (&obj > tree[n]) { n = 2*n+1; return search_helper(n, obj); } else { n = 2*n; return search_helper(n, obj); } } ),并且没有边界检查要么。