Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check/find if an item is in a DEQUE

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

like image 350
george mano Avatar asked Jan 19 '12 17:01

george mano


People also ask

How do you check if something is in a deque?

deque class to initialize a deque object, you can directly use the in operator to check if an item is in the deque. Copied! The collections. deque class has atomic append() , implements the popleft() method and supports indexing and membership testing.

Can you iterate through a deque?

You can directly iterate over the deque.

Which methods from std :: deque class can be used to check if there are elements in the container?

empty() function is used to check if the deque container is empty or not. size() function is used to return the size of the deque container or the number of elements in the deque container.

Does deque have an index?

std::deque (double-ended queue) is an indexed sequence container that allows fast insertion and deletion at both its beginning and its end. In addition, insertion and deletion at either end of a deque never invalidates pointers or references to the rest of the elements.


1 Answers

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.

like image 104
kennytm Avatar answered Oct 17 '22 04:10

kennytm