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

前端 未结 10 1879
情深已故
情深已故 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 09:10

    Get rid of the notion of vector entirely

    template< typename IT, typename VT>
    int index_of(IT begin, IT end, const VT& val)
    {
        int index = 0;
        for (; begin != end; ++begin)
        {
            if (*begin == val) return index;
        }
        return -1;
    }
    

    This will allow you more flexibility and let you use constructs like

    int squid[] = {5,2,7,4,1,6,3,0};
    int sponge[] = {4,2,4,2,4,6,2,6};
    int squidlen = sizeof(squid)/sizeof(squid[0]);
    int position = index_of(&squid[0], &squid[squidlen], 3);
    if (position >= 0) { std::cout << sponge[position] << std::endl; }
    

    You could also search any other container sequentially as well.

提交回复
热议问题