首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C++:我可以使用带有新位置的向量吗?

C++:我可以使用带有新位置的向量吗?
EN

Stack Overflow用户
提问于 2013-06-18 19:16:52
回答 1查看 1.1K关注 0票数 2

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

代码语言:javascript
复制
#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();
}

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

另外,是否有一种更干净的方法来设置键和数据的指针?欢迎提供任何协助或建议。

EN

回答 1

Stack Overflow用户

发布于 2013-06-18 20:01:17

你对num的计算

代码语言:javascript
复制
(NODE_SIZE - sizeof( Node<K,D> ) - sizeof( long )) / (sizeof( D ) + sizeof( K ))

值得注意的是编译时常数。为什么不简单地宣布:

代码语言:javascript
复制
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 );
};

让编译器为你做这件事?

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17177052

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档