Prasanth Madhavan Prasanth Madhavan - 1 year ago 88
C++ Question

How to search for an element in an stl list?

Is there a

function for list as there was in vector?

Is there a way to do that in list?

Answer Source

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

#include <list>
#include <algorithm>

int main()
    std::list<int> ilist;

    std::list<int>::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