How to search for an element in an stl list?

后端 未结 5 997
南旧
南旧 2020-12-04 19:13

Is there a find() function for list as there was in vector?

Is there a way to do that in list?

5条回答
  •  臣服心动
    2020-12-04 19:50

    Besides using std::find (from algorithm), you can also use std::find_if (which is, IMO, better than std::find), or other find algorithm from this list


    #include 
    #include 
    #include 
    
    int main()
    {
        std::list myList{ 5, 19, 34, 3, 33 };
        
    
        auto it = std::find_if( std::begin( myList ),
                                std::end( myList ),
                                [&]( const int v ){ return 0 == ( v % 17 ); } );
            
        if ( myList.end() == it )
        {
            std::cout << "item not found" << std::endl;
        }
        else
        {
            const int pos = std::distance( myList.begin(), it ) + 1;
            std::cout << "item divisible by 17 found at position " << pos << std::endl;
        }
    }
    

提交回复
热议问题