通过size_t索引迭代到boost :: multi_index中的顺序位置?

时间:2011-05-05 12:25:44

标签: c++ boost

我刚开始使用boost multi_index,到目前为止还有一个容器,它包含一个序列类型和复合键无序哈希值。

我想要做的是访问已排序的容器,就像它是std :: vector或std :: list一样。我的意思是通过使用size_t index

以下是我的代码:

// tags
struct linear { };
struct semantic { };
struct semantic_and_index { };

// typedefs for multi_index
typedef boost::multi_index::sequenced< 
    boost::multi_index::tag<linear>
> LinearIndex;

typedef boost::multi_index::composite_key<
    CVertexElement,
    boost::multi_index::const_mem_fun<CVertexElement, Buffer::VertexSemantic, &CVertexElement::GetVertexSemantic>,
    boost::multi_index::const_mem_fun<CVertexElement, UInt, &CVertexElement::GetSemanticIndex> 
> CompositeSemanticIndex;

typedef boost::multi_index::hashed_non_unique<
    boost::multi_index::tag<semantic_and_index>,
    CompositeSemanticIndex
> SemanticAndIDIndex;

typedef boost::multi_index::hashed_non_unique<
    boost::multi_index::tag<semantic>,
    boost::multi_index::const_mem_fun<CVertexElement, Buffer::VertexSemantic, &CVertexElement::GetVertexSemantic> 
> SemanticIndex;

class CVertexFormat
{
public:
    typedef boost::multi_index::multi_index_container <
        CVertexElementPtr,
        boost::multi_index::indexed_by <
            LinearIndex,
            SemanticAndIDIndex,
            SemanticIndex
        > // index_by
    > ElementContainer; 

      // etc...

protected:
    ElementContainer m_elements;
};

我所指的功能是:

// this function fails! :(
CVertexElementPtr CVertexFormat::GetElement(size_t index) const 
{
    //sequenced_index.
    typedef ElementContainer::index<linear>::type element_by_linear;
    const element_by_linear& index_type = m_elements.get<linear>();

    if ( index < index_type.size() )
    {
        auto itor = index_type.begin();
        for (UInt i = 0; i < index_type.size(); ++i)
            ++itor;

        const CVertexElementPtr& pElement = (*itor);        
        return pElement;
    }
    else
    {
        assert(!"Invalid index called for GetElement");
        return CVertexElementPtr();
    }
}

vs2010中的错误图片(请查看右侧的观察窗口):

High res screen shot

1 个答案:

答案 0 :(得分:0)

通过更改函数CVertexElementPtr CVertexFormat::GetElement(size_t index) const来解决问题。

正确的功能是:

CVertexElementPtr CVertexFormat::GetElement(size_t index) const
{
    //sequenced_index.
    typedef ElementContainer::index<linear>::type element_by_linear;
    const element_by_linear& index_type = m_elements.get<linear>();

    size_t size = index_type.size();
    if ( index < size )
    {
        auto itor = index_type.begin();
        for (UInt i = 0; i < index; ++i)
            ++itor;

        const CVertexElementPtr& pElement = (*itor);        
        return pElement;
    }
    else
    {
        assert( false && ieS("Invalid index called for GetElement") );
        return CVertexElementPtr();
    }
}