How to get the index of a value in a vector using for_each?

前端 未结 10 672
[愿得一人]
[愿得一人] 2020-12-28 14:02

I have the following code (compiler: MSVC++ 10):

std::vector data;
data.push_back(1.0f);
data.push_back(1.0f);
data.push_back(2.0f);

// lambda          


        
10条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-28 14:22

    Something like this:

    template 
    FunctionT enumerate(IteratorT first, 
                        IteratorT last, 
                        typename std::iterator_traits::difference_type initial,
                        FunctionT func)
    {
        for (;first != last; ++first, ++initial)
            func(initial, *first);
        return func;
    }
    

    Used as:

    enumerate(data.begin(), data.end(), 0, [](unsigned index, float val)
    {
        std::cout << index << " " << val << std::endl;
    });
    

提交回复
热议问题