2

我正在这里进行一些思想实验——我正在努力让我的生活更轻松。我正在使用一种数据结构,其中包含几个按排序顺序保存的元素数组。我将这些数据结构分配在固定大小的块中,以便更轻松地放置内存,并且(在未来)更容易从稳定存储中读取/写入。这是我目前正在使用的代码:

#include <limits>

const int NODE_SIZE = 512;

template <typename K, typename D>
class Node {
    long   next;
    short  num;
    K*     keys;
    D*     data;
public:
    Node( int l, int order );
};

// num is calculated by something like this...
num = NODE_SIZE - sizeof( Node<K,D> ) - sizeof( long );
num /= (sizeof( D ) + sizeof( K ));

// Constructor
//     Will be called with a placement-new and given a NODE_SIZE
//     byte block of memory, aligned at NODE_SIZE
template<typename K, typename D>
Node<K,D>::Node( int n ) : num ( n ), next( 0 ) {
    keys = reinterpret_cast<K*>(reinterpret_cast<char*>(&next) +
                                sizeof( *this ));

    int numbytes = num*sizeof(K);
    // Make sure we're aligned to a void *.
    if ( numbytes % sizeof( void * ) ) {
        numbytes = (numbytes / sizeof( void * )+1)*sizeof( void * );
    }

    // Align to the number of bytes in a void *
    data = reinterpret_cast<D*>( reinterpret_cast<char*>(keys)+numbytes);

    for( int i=0; i<num; i++ ) keys[i] = std::numeric_limits<K>::max();
}

由于 key 中的元素是按排序顺序排列的,我真的很希望能够使用 std::vector 和 std::vector 这样我就可以使用其他人的向量插入代码而不是自己编写(不是很难,而是为什么要重新发明轮子?)。

另外,有没有更简洁的方法来设置我的键和数据指针?欢迎任何帮助或建议。

4

1 回答 1

2

您的计算num

(NODE_SIZE - sizeof( Node<K,D> ) - sizeof( long )) / (sizeof( D ) + sizeof( K ))

尤其是编译时常数。为什么不简单地声明:

template <typename K, typename D>
class BpTreeNode {
    static const std::size_t num = (NODE_SIZE - sizeof( long )) /
                                   (sizeof( D ) + sizeof( K ));
    K    keys[num];
    D    data[num];
    long next;
public:
    Node( int l, int order );
};

并让编译器为您完成工作?

于 2013-06-18T20:01:17.707 回答