объявление массива узлов

Я пытаюсь инициализировать массив узлов в классе узлов, они являются частными членами:

    #include<iostream>
#include<string>
using namespace std;
class Data
{
public:
long data;
Data(long dd)
{
data=dd;
}
void displaydata()
{
cout<<data <<"  "<<endl;
}
};
class node
{
//these are what i have changed
const static int order=4;
int numitems;
node *parent;vector<node>childarray(order);
vector<Data>itemarray(order-1);

};

но, к сожалению, он не компилируется, ошибки:

  1>c:\users\dato\documents\visual studio 2010\projects\234_tree\234_tree\234_tree.cpp(26): error C2061: syntax error : identifier 'order'
1>c:\users\dato\documents\visual studio 2010\projects\234_tree\234_tree\234_tree.cpp(27): error C2061: syntax error : identifier 'order'
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

Из следующего кода Java.

class DataItem
{
public long dData; // one data item
//--------------------------------------------------------------
public DataItem(long dd) // constructor
{ dData = dd; }
//--------------------------------------------------------------
public void displayItem() // display item, format “/27”
{ System.out.print(“/”+dData); }
//--------------------------------------------------------------
} // end class DataItem
////////////////////////////////////////////////////////////////
class Node
{
private static final int ORDER = 4;
private int numItems;
private Node parent;
private Node childArray[] = new Node[ORDER];
private DataItem itemArray[] = new DataItem[ORDER-1];
// -------------------------------------------------------------
// connect child to this node
public void connectChild(int childNum, Node child)
{
childArray[childNum] = child;
if(child != null)
child.parent = this;
}
// -------------------------------------------------------------
// disconnect child from this node, return it
public Node disconnectChild(int childNum)
{
Node tempNode = childArray[childNum];
childArray[childNum] = null;
return tempNode;
}
// -------------------------------------------------------------
public Node getChild(int childNum)
{ return childArray[childNum]; }
// -------------------------------------------------------------
public Node getParent()
{ return parent; }
// -------------------------------------------------------------
public boolean isLeaf()
Java Code for a 2-3-4 Tree 479
LISTING 10.1 Continued
{ return (childArray[0]==null) ? true : false; }
// -------------------------------------------------------------
public int getNumItems()
{ return numItems; }
// -------------------------------------------------------------
public DataItem getItem(int index) // get DataItem at index
{ return itemArray[index]; }
// -------------------------------------------------------------
public boolean isFull()
{ return (numItems==ORDER-1) ? true : false; }
// -------------------------------------------------------------
public int findItem(long key) // return index of
{ // item (within node)
for(int j=0; j<ORDER-1; j++) // if found,
{ // otherwise,
if(itemArray[j] == null) // return -1
break;
else if(itemArray[j].dData == key)
return j;
}
return -1;
} // end findItem
// -------------------------------------------------------------
public int insertItem(DataItem newItem)
{
// assumes node is not full
numItems++; // will add new item
long newKey = newItem.dData; // key of new item
for(int j=ORDER-2; j>=0; j--) // start on right,
{ // examine items
if(itemArray[j] == null) // if item null,
continue; // go left one cell
else // not null,
{ // get its key
long itsKey = itemArray[j].dData;
if(newKey < itsKey) // if it’s bigger
itemArray[j+1] = itemArray[j]; // shift it right
else
{
itemArray[j+1] = newItem; // insert new item

Пожалуйста, помогите мне легко конвертировать код. Должен ли я объявить заказ публичным? Я пытался, но это не работает, я также пытался объявить порядок вне класса, как
const int node :: order = 4
но пока не удалось, в чем проблема? Мне нужен массив, который содержит члены, размер должен быть порядка или 4. Когда я читал книгу, автор сказал, что вам нужно, когда я пишу код Java на C ++ из этой книги, он говорит указатель, поэтому я добавил указатель, но пока безуспешно.

0

Решение

Линии

node *childarray[]=new node[order];
Data *itemarray[]=new Data[order-1];

здесь по ошибке. Помимо того, что вы не можете назначить подобное в классе, у вас также есть неправильное объявление. Вы заявляете, например, childarray быть массивом указателей, но вы создаете его как простой массив. Изменить объявления на

node *childarray;
Data *itemarray;

Чтобы на самом деле сделать распределение, вы должны сделать это в конструкторе.

Тем не менее, я очень рекомендую вам использовать std::array (или возможно std::vector) вместо

Редактировать: С помощью std::array:

struct node
{
static const int ORDER = 4;
int numitems;
node* parent;
std::array<node*, ORDER> childarray;
std::array<Data*, ORDER - 1> itemarray;

node()
: numitems{0},
parent{nullptr},
childarray{{nullptr}},
itemarray{{nullptr}}
{ }
};

Сейчас childarray а также itemarray являются массивами с ORDER а также ORDER - 1 (соответственно) количество указателей, все инициализированы в nullptr (какие NULL должен сейчас).

1

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector