BOOST_FOREACH在指针向量上

时间:2014-06-02 16:43:25

标签: c++ boost

我想使用BOOST_FOREACH宏来迭代我vector中的一堆值。矢量看起来像这样:

struct _Element
{
    int key;
    // more variables here
}

elements = new std::vector<_Element *>;

我对C ++很陌生,而且我对如何实际迭代所包含的_Element *感到有些困惑。为什么这不起作用?

BOOST_FOREACH(_Element *currentElem, rootElement->_document->elements)
{
    // do stuff
}

编译这会给我一个错误:

shared.cc:146:37: error: no viable conversion from 'std::__1::vector<_Element *, std::__1::allocator<_Element *> >' to '_Element *'
    BOOST_FOREACH(_Element *currentElem, rootElement->_document->elements)
    ~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

4 个答案:

答案 0 :(得分:3)

elements的类型为vector<_Element *>*,因此您需要在将其传递给BOOST_FOREACH之前取消引用它。

BOOST_FOREACH(_Element *currentElem, *(rootElement->_document->elements))
{
    // do stuff
}

这将解决编译错误,但由于您是C ++的新手,因此很有可能您不需要所有已声明的指针。例如,您的代码应该如下所示:

struct Element            // do not use leading underscore followed by 
                          // uppercase letter, that's reserved
{
    int key;
    // more variables here
};

std::vector<Element> elements = std::vector<Element>;
// vector of Element, not Element*. And elements is a vector, not vector *

最后,如果您的编译器支持基于C ++ 11范围的for,那么您不需要BOOST_FOREACH

for(auto&& currentElem : rootElement.document.elements)
// notice that I've gotten rid of all the pointers within rootElement
{
  // currentElem is a reference to the current element in the elements vector
}

答案 1 :(得分:2)

声明

elements = new std::vector<_Element *>;

表示elements是指针类型。

技术上表示您需要取消引用*elements,以便与BOOST_FOREACH一起使用。

但在良好的编程实践水平上,这仍然是完全错误的。

相反:

  • elements直接成为vector。不是指针。

  • 请勿使用new

  • 如果您的编译器支持,请使用C ++ 11 基于范围的for 。如果没有,那么升级您的编译器并使用基于C ++ 11范围的for

它看起来像这样:

for( auto const& item : elements )
{
    // Do whatever
}

或者如果这些项目是小型/简单的类型,那么一些有价值的复制并不重要,只需

for( auto const item : elements )
{
    // Do whatever
}

顺便说一句:除了避免不必要的大型库依赖关系,并避免在可行的情况下使用原始指针,您可能需要重新考虑使用前缀下划线作为成员名称约定。前缀下划线由许多其他软件使用,并在全局命名空间中保留。一个不错的选择是后缀下划线。

答案 2 :(得分:0)

BOOST_FOREACH期望容器不是指向容器的指针作为第二个参数。

使用

BOOST_FOREACH(_Element *currentElem, *(rootElement->_document->elements))
{
    // do stuff
}

答案 3 :(得分:0)

做:

BOOST_FOREACH(_Element *currentElem, *(rootElement->_document->elements))
{
   .....
}

或者如果您的编译器支持C ++ 11,则更喜欢使用内置范围迭代:

for(auto element : *(rootElement->_document->elements))
{
   ....
}