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

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

    You probably should not use your own function here. Use find() from STL.

    Example:

    list L;
    L.push_back(3);
    L.push_back(1);
    L.push_back(7);

    list::iterator result = find(L.begin(), L.end(), 7); assert(result == L.end() || *result == 7);

    0 讨论(0)
  • First of all, do you really need to store indices like this? Have you looked into std::map, enabling you to store key => value pairs?

    Secondly, if you used iterators instead, you would be able to return std::vector.end() to indicate an invalid result. To convert an iterator to an index you simply use

    size_t i = it - myvector.begin();
    
    0 讨论(0)
  • 2021-01-31 09:09

    If a vector has N elements, there are N+1 possible answers for find. std::find and std::find_if return an iterator to the found element OR end() if no element is found. To change the code as little as possible, your find function should return the equivalent position:

    size_t find( const vector<type>& where, int searchParameter )
    {
       for( size_t i = 0; i < where.size(); i++ ) {
           if( conditionMet( where[i], searchParameter ) ) {
               return i;
           }
        }
        return where.size();
    }
    // caller:
    const int position = find( firstVector, parameter );
    if( position != secondVector.size() ) {
        doAction( secondVector[position] );
    }
    

    I would still use std::find_if, though.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题