0

I am using boost 1.55.0 and want to iterate through a property tree and I need the index of the iterator.

I used the answer from this question: What is the most effective way to get the index of an iterator of an std::vector?

The for loop and the try to obtain the index look like:

boost::property_tree::ptree sensors;
for(boost::property_tree::ptree::const_iterator it = sensors.begin(); it != sensors.end(); ++it)
{           
    auto idx = it - sensors.begin();
}

But I get this compiler error:

/Boost1p55p0/build/include/boost/iterator/iterator_adaptor.hpp:224:7: error: 
  static_assert failed "(is_convertible<Tr1, Tr2>::value)"
  BOOST_STATIC_ASSERT((is_convertible<Tr1, Tr2>::value));
  ^                   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
........
in instantiation of function template specialization
  'boost::operator-<boost::property_tree::basic_ptree<std::basic_string<char>,
  std::basic_string<char>, std::less<std::basic_string<char> > >::const_iterator,
  std::pair<const std::basic_string<char>,
  boost::property_tree::basic_ptree<std::basic_string<char>, std::basic_string<char>,
  std::less<std::basic_string<char> > > >, boost::bidirectional_traversal_tag, const
  std::pair<const std::basic_string<char>,
  boost::property_tree::basic_ptree<std::basic_string<char>, std::basic_string<char>,
  std::less<std::basic_string<char> > > > &, long,
  boost::property_tree::basic_ptree<std::basic_string<char>, std::basic_string<char>,
  std::less<std::basic_string<char> > >::iterator, std::pair<const
  std::basic_string<char>, boost::property_tree::basic_ptree<std::basic_string<char>,
  std::basic_string<char>, std::less<std::basic_string<char> > > >,
  boost::bidirectional_traversal_tag, std::pair<const std::basic_string<char>,
  boost::property_tree::basic_ptree<std::basic_string<char>, std::basic_string<char>,
  std::less<std::basic_string<char> > > > &, long>' requested here
            auto idxIt = it - sensors.begin();

What is wrong, and how can I obtain the index as uint?

I am using ubuntu 12.04 LTS with clang 3.4.

Community
  • 1
  • 1
Rico-E
  • 1,806
  • 2
  • 28
  • 47
  • Iterators don't necessarily support arbitrary moves. "Index" is not necessarily available (and sensible), especially for complex structures like trees or hashes. – user3159253 Feb 07 '14 at 09:55
  • so there is no other way, to obtain the index than to count how often the iterator got increased? For example have another variable counting the cycles of the for loop. – Rico-E Feb 07 '14 at 10:10

1 Answers1

0

Well, you may check if std::distance is suitable for your needs. But remember that counting distance for iterators which don't support random access may lead to O(N) operations (N ++-es)

user3159253
  • 16,836
  • 3
  • 30
  • 56