如何在 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
是一个指向序列开头的迭代器。如果等于大海捞针的尽头,就没有针。
相关文章:
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- 在c++中用vector填充一个简单的动态数组
- vector.resize()中的分配错误
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 使用std::vector的OpenCL矩阵乘法
- POCO::PostgreSQL:如何将std::vector支持添加到`Binder::bind`
- 在某些循环内使用vector.push_back时出现分段错误
- 当vector是tje全局变量时,c++中vector的内存管理
- std::vector的包装器,使数组的结构看起来像结构的数组
- 为什么在保护模式下继承升级不起作用
- 如何在全屏模式下(在OpenGL中)使背景透明
- 为什么(-1)%vector::size()总是返回0
- 为什么使用__LINE_的代码在发布模式下在MSVC下编译,而不是在调试模式下
- 派生类是否可以在抽象工厂设计模式中具有数据成员
- 基于 std::vector <string>的内容动态设置顺序的模式
- 在C++中存储多种结构的模式 std::<vector> 容器
- 使用重复模式初始化std::vector
- vector insert中重载模板函数选择(模式匹配)是如何工作的
- 设计模式-C++Decorator添加到std::vector中
- 如何在 std::vector 中找到模式