如何在 std::vector 中找到模式

How to find a pattern in std::vector

本文关键字:模式 vector std      更新时间:2023-10-16

是否有任何直接的方法可以查找std::vector容器中是否存在一组特定的值(模式)?

假设我有这个数据容器:

std::vector<int> data { 0x00, 0xff, 0x00, 0x11, 0x12, 0x13, 0x14, 0x15 };

此模式使用另一个std::vector容器进行描述:

std::vector<int> pattern { 0x00, 0xff, 0x00 };

我想要:

  • 表示模式存在的布尔值。

  • 最终,模式开始的索引。

您可以使用

std::search .

#include <iostream>
#include <vector>
#include <algorithm>
int main() {
    std::vector<int> data {0x00, 0xff, 0x00, 0x11, 0x12, 0x13, 0x14, 0x15};
    std::vector<int> pattern {0x00, 0xff, 0x00};
    auto res = std::search(std::begin(data), std::end(data), std::begin(pattern), std::end(pattern));
    if(res == std::end(data)) {
        std::cout << "Couldn't find it.n";
    } else {
        std::cout << "Found it.n";
    }
}

在这里,res是一个指向序列开头的迭代器。如果等于大海捞针的尽头,就没有针。