How do I find an element position in std::vector?

前端 未结 10 1874
情深已故
情深已故 2021-01-31 08:40

I need to find an element position in an std::vector to use it for referencing an element in another vector:

int find( const vector& whe         


        
10条回答
  •  既然无缘
    2021-01-31 08:48

    Something like this, I think. find_if_counted.hpp:

    #ifndef FIND_IF_COUNTED_HPP
    #define FIND_IF_COUNTED_HPP
    
    #include 
    
    namespace find_if_counted_impl
    {
        template 
        struct func_counter
        {
            explicit func_counter(Func& func, unsigned &count) :
            _func(func),
            _count(count)
            {
            }
    
            template 
            bool operator()(const T& t)
            {
                ++_count;
    
                return _func(t);
            }
    
        private:
            Func& _func;
            unsigned& _count;
        };
    }
    
    // generic find_if_counted,
    // returns the index of the found element, otherwise returns find_if_not_found
    const size_t find_if_not_found = static_cast(-1);
    
    template 
    size_t find_if_counted(InputIterator start, InputIterator finish, Func func)
    {
        unsigned count = 0;
        find_if_counted_impl::func_counter f(func, count);
    
        InputIterator result = find_if(start, finish, f);
    
        if (result == finish)
        {
            return find_if_not_found;
        }
        else
        {
            return count - 1;
        }
    }
    
    #endif
    

    Example:

    #include "find_if_counted.hpp"
    #include 
    #include 
    #include 
    
    typedef std::vector container;
    
    int rand_number(void)
    {
        return rand()  % 20;
    }
    
    bool is_even(int i)
    {
        return i % 2 == 0;
    }
    
    int main(void)
    {
        container vec1(10);
        container vec2(10);
    
        std::generate(vec1.begin(), vec1.end(), rand_number);
        std::generate(vec2.begin(), vec2.end(), rand_number);
    
        unsigned index = find_if_counted(vec1.begin(), vec1.end(), is_even);
    
        if (index == find_if_not_found)
        {
            std::cout << "vec1 has no even numbers." << std::endl;
        }
        else
        {
            std::cout << "vec1 had an even number at index: " << index <<
                " vec2's corresponding number is: " << vec2[index] << std::endl;
        }
    }
    

    Though I feel like I'm doing something silly... :X Any corrections are welcome, of course.

提交回复
热议问题