Get index in C++11 foreach loop

后端 未结 5 869
太阳男子
太阳男子 2020-12-28 12:55

Is there a convenient way to get the index of the current container entry in a C++11 foreach loop, like enumerate in python:

for idx, obj in enu         


        
5条回答
  •  [愿得一人]
    2020-12-28 13:40

    A good implementation of the feature you are requested can be found here:

    https://github.com/ignatz/pythonic

    The idea behind is, that you build a wrapper struct with a custom iterator that does the counting. Below is a very minimal exemplary implementation to illustrate the idea:

    #include 
    #include 
    #include 
    
    // Wrapper class
    template 
    class enumerate_impl
    {
    public:
        // The return value of the operator* of the iterator, this
        // is what you will get inside of the for loop
        struct item
        {
            size_t index;
            typename T::value_type & item;
        };
        typedef item value_type;
    
        // Custom iterator with minimal interface
        struct iterator
        {
            iterator(typename T::iterator _it, size_t counter=0) :
                it(_it), counter(counter)
            {}
    
            iterator operator++()
            {
                return iterator(++it, ++counter);
            }
    
            bool operator!=(iterator other)
            {
                return it != other.it;
            }
    
            typename T::iterator::value_type item()
            {
                return *it;
            }
    
            value_type operator*()
            {
                return value_type{counter, *it};
            }
    
            size_t index()
            {
                return counter;
            }
    
        private:
            typename T::iterator it;
            size_t counter;
        };
    
        enumerate_impl(T & t) : container(t) {}
    
        iterator begin()
        {
            return iterator(container.begin());
        }
    
        iterator end()
        {
            return iterator(container.end());
        }
    
    private:
        T & container;
    };
    
    // A templated free function allows you to create the wrapper class
    // conveniently 
    template 
    enumerate_impl enumerate(T & t)
    {
        return enumerate_impl(t);
    }
    
    
    
    int main()
    {
        std::vector data = {523, 1, 3};
        for (auto x : enumerate(data))
        {
            std::cout << x.index << ": " << x.item << std::endl;
        }
    }
    

提交回复
热议问题