How to check/find if an item is in a DEQUE
37,530
Solution 1
If std::find
cannot find the specific value, it will return the "end" of the iterator pair.
else if (std::find(visited.begin(), visited.end(), x) == visited.end())
{
// process the case where 'x' _is_not_ found between
// visited.begin() and visited.end()
Edit: If you want to know if x is in the deque, just reverse the condition.
else if (std::find(visited.begin(), visited.end(), x) != visited.end())
{
// process the case where 'x' _is_ found between
// visited.begin() and visited.end()
Edit: If you are unfamiliar with the iterator concept in C++, please read Understanding Iterators in the STL.
Solution 2
For those who visited this page to simply know how to check/find elements in dequeue. A quick solution is as below:
Use std::find() method:
numbers.push_back(10);
numbers.push_front(20);
numbers.push_back(30);
numbers.push_front(40);
deque<int>::iterator it = find(numbers.begin(), numbers.end(), 20);
if(it!=numbers.end())
{
// Do your stuff. Here I am simply deleting the element
it = numbers.erase(it);
// Note: Always save returned iterator from erase/insert method, otherwise
// iterator will point to deleted resource, which leads to undefined behaviour.
}
Hope this will help somebody. :)
Author by
george mano
Updated on July 18, 2022Comments
-
george mano almost 2 years
In the code above the else-if part gives me error. The meaning of else-if is: else if the value of x isn't in the deque then...
#include <iostream> #include <ctime> #include <stack> #include <deque> #include <algorithm> deque<char> visited; char x; if (x==target[4][4]) { visited.push_back(x); return (visited); } else if (!(find(visited.begin(), visited.end(), x))) { visited.push_back(x); }
ERROR:no operator "!" matches these operands
-
kennytm over 12 years@georgemano: It cannot.
.end()
points to the location after the back of the deque.