boost::adaptors::index

References

Headers

boost::adaptors::index is available by including any of the following headers:

  • boost/range/adaptor/indexed.hpp or
  • boost/range/adaptors.hpp

Examples

indexed-function.cpp

#include <iostream>
#include <string>
#include <vector>

// The index() implementation in Boost < 1.56 can't be recommended.
// It's clunky and doesn't work with range-based for loops.
// If you can't upgrade, grab the backported "boost-range-indexed-1.56.hpp" and
// "boost-range-traversal-1.56.hpp from this repo. They have to be included
// before other Boost Range headers.
#include "boost-range-indexed-1.56.hpp"
#include <boost/range/adaptors.hpp>

const std::string str = "beebop";


int main() {
    // index() is analogous to Python's enumerate(). Given a Range,
    // it gives access to the elements as well as their indices.
    // Boost 1.56 or higher is required for this to work properly.
    //
    // The (optional) parameter sets the index of the first element (default: 0)
    std::cout << "Enumeration of a string" << std::endl;
    for (const auto & element : boost::adaptors::index(str, 0)) {
        std::cout << element.index()
                  << " : "
                  << element.value()
                  << std::endl;
    }

    return 0;
}

Output:

Enumeration of a string
0 : b
1 : e
2 : e
3 : b
4 : o
5 : p

 

Boost Range for Humans

This reference is part of Boost Range for Humans. Click the link to the overview.