c# - C++等价物。 C# 的 intQueue.Contains()

标签 c# c++ queue translate fifo

我正在将大量代码从 C# 转换为 C++,但我遇到了一个看似基本的问题。

我想做一个简单的评估,看看 int 的 FIFO 队列是否包含特定的 int。这并不难做到,但我似乎无法在 Google 上找到一个好的例子。

if(intQueue.Contains(value)){ /* do some stuff */ }

我在 here 上发现了同样的问题,但答案并不真正适用于我的情况。请帮忙!谢谢!

最佳答案

我可能会使用 std::find()位于<algorithm> .您需要将开始和结束迭代器传递给它,这不能使用 queue 访问类,所以一个很好的选择是 deque .

双端队列的功能类似于队列,因为可以将项目从其中压入和弹出,但项目不限于“先进先出”模型。可以从后面和前面弹出和插入元素。 queue是这样的默认情况下,类在内部存储其元素。

#include <deque>
#include <algorithm>
#include <iostream>

int main()
{
    // initialize deque with ints 3, 2, 1
    std::deque<int> intDeque{ 3, 2, 1 };

    auto it = std::find(intDeque.begin(), intDeque.end(), 2); // find 2 in intDeque

    if (it == intDeque.end()) {
        std::cout << "Not found" << std::endl;
    }
    else {
        std::cout << "Found!" << std::endl;
    }

    return 0;
}

上面使用的是c++11,如果你没有权限,你可以这样做:

std::deque<int> intDeque;
// push elements onto the deque
intDeque.push_back(3);
intDeque.push_back(2);
intDeque.push_back(1);

std::deque<int>::iterator it = std::find(intDeque.begin(), intDeque.end(), 2); // find 2 in intDeque

关于c# - C++等价物。 C# 的 intQueue.Contains(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38537741/

相关文章:

c++ - 空间有限的优先级队列 : looking for a good algorithm

c# - WPF 控件的嵌套属性的数据绑定(bind)

c# - 在几个类中干燥 ICloneable 的实现

c# - 通过任意排序表达式对列表进行排序?

c++ - 从各种列表中收集条目的迭代器列表

c++ - 一次创建多个队列

events - 如何在 laravel 中使用 Event::queue?

c# - 在 .NET : good, 中隐藏继承的通用接口(interface)成员是坏的还是丑的?

c++ - 如何为流式自写类编写用户定义的操纵器

c++ - 使用 Restbed 时出现链接器错误