如何在 std::vector 中找到模式
How to find a pattern in std::vector
是否有任何直接的方法来查找 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
是一个指向序列开头的迭代器。等于大海捞针,没有针
是否有任何直接的方法来查找 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
是一个指向序列开头的迭代器。等于大海捞针,没有针