How to search for an element in an stl list?

后端 未结 5 990
南旧
南旧 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:47

    You use std::find from , which works equally well for std::list and std::vector. std::vector does not have its own search/find function.

    #include 
    #include 
    
    int main()
    {
        std::list ilist;
        ilist.push_back(1);
        ilist.push_back(2);
        ilist.push_back(3);
    
        std::list::iterator findIter = std::find(ilist.begin(), ilist.end(), 1);
    }
    

    Note that this works for built-in types like int as well as standard library types like std::string by default because they have operator== provided for them. If you are using using std::find on a container of a user-defined type, you should overload operator== to allow std::find to work properly: EqualityComparable concept

提交回复
热议问题