C++ 如何检查/查找项目是否在 DEQUE 中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8930417/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 19:21:00  来源:igfitidea点击:

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

c++algorithmdata-structuresartificial-intelligence

提问by george mano

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

在上面的代码中,else-if 部分给了我错误。else-if 的意思是:else 如果 x 的值不在双端队列中,那么...

#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

错误:没有运算符“!” 匹配这些操作数

回答by kennytm

If std::findcannot find the specific value, it will return the "end" of the iterator pair.

如果std::find找不到特定值,它将返回迭代器对的“结束”。

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 xisin the deque, just reverse the condition.

编辑:如果您想知道x是否在双端队列中,只需反转条件即可。

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.

编辑:如果您不熟悉 C++ 中的迭代器概念,请阅读了解 STL 中的迭代器

回答by Hridaynath

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:

使用std::find()方法:

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

希望这会帮助某人。:)