10

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

george mano
  • 5,948
  • 6
  • 33
  • 43

2 Answers2

23

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.

Community
  • 1
  • 1
kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005
9

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. :)

Hridaynath
  • 497
  • 5
  • 4