Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to search for an element in an stl list?

Tags:

c++

stl

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

Is there a way to do that in list?

like image 202
Prasanth Madhavan Avatar asked Jan 05 '11 12:01

Prasanth Madhavan


People also ask

How do you find items in a list C++?

In std::find() you can pass two iterators and a value. It will iterate all the elements between 2 given iterators and compare the given val with each one. If any match is found, then it will immediately return that iterator, else it returns the iterator pointing to end of list.

What does find function in STL return?

find() function is an inbuilt function in C++ STL, which is defined in header file. This function is used to find an element or a value in a set container. find() returns an iterator which points to the position of the element which is searched.

How do you check if a list contains an element in C++?

Use the any_of() Function to Check if an Array Contains an Element in C++ We can use the any_of() function to check if a predicate conforms to any elements present in a given range. If yes, it returns true ; else, it returns false .


Video Answer


1 Answers

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;     ilist.push_back(1);     ilist.push_back(2);     ilist.push_back(3);      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

like image 64
逆さま Avatar answered Oct 13 '22 15:10

逆さま