C++在矢量<uint8_t>中查找uint8_t
C++ finding uint8_t in vector<uint8_t>
我有以下简单的代码。在这种情况下,我声明一个向量并用一个值 21 初始化它。然后我尝试使用 find 在向量中找到该值。我可以看到在这种情况下元素"21"在向量中,因为我在 for 循环中打印它。但是,为什么 find 的迭代器不解析为 true?
vector<uint8_t> v = { 21 };
uint8_t valueToSearch = 21;
for (vector<uint8_t>::const_iterator i = v.begin(); i != v.end(); ++i){
cout << unsigned(*i) << ' ' << endl;
}
auto it = find(v.begin(), v.end(), valueToSearch);
if ( it != v.end() )
{
string m = "valueToSearch was found in the vector " + valueToSearch;
cout << m << endl;
}
你确定它不起作用吗?
我刚刚尝试过:
#include<iostream> // std::cout
#include<vector>
#include <algorithm>
using namespace std;
int main()
{
vector<uint8_t> v = { 21 };
uint8_t valueToSearch = 21;
for (vector<uint8_t>::const_iterator i = v.begin(); i != v.end(); ++i){
cout << unsigned(*i) << ' ' << endl;
}
auto it = find(v.begin(), v.end(), valueToSearch);
if ( it != v.end() )
{// if we hit this condition, we found the element
string error = "valueToSearch was found in the vector ";
cout << error << int(valueToSearch) << endl;
}
return 0;
}
有两个小的修改:
在"if"内的最后一行,因为您无法直接添加 数字到字符串:
string m = "valueToSearch was found in the vector " + valueToSearch;
它打印:
21
valueToSearch was found in the vector 21
虽然您确实不能将数字添加到字符串中,但 Cout 支持 int 类型的插入运算符 (<<(,但不支持 uint8_t, 所以你需要把它转换成它。
cout << error << int(valueToSearch) << endl;
这表示查找工作正常,它告诉您它在第一个位置找到了数字,为此,it != end
(end 不是有效元素,而是标记容器末尾的有效迭代器。
在这里尝试一下
相关文章:
- EASTL矢量<向量<int>>连续的
- 从值小于256的uint16到uint8的Endian安全转换
- 你能把一个向量<int64>投射到一个向量<uint8>吗
- SSCANF 进入 uint8 阵列失败
- 着色器将uint8投射到float,并将其重新解释回uint
- 将指针uint8覆盖到指针uint16
- 创建一个包含30亿个uint8元素的向量
- 将 Uint8(浮点AUDIO_F32)转换为int16_t(16 位 PCM)
- UINT8/16 /32/etc 和 INT8/16/32/etc 在 libtiff 中不起作用?
- 错误:无法将'uint8* {aka unsigned int*}'转换为"常量emxArray_uint8_T*"?
- C - 创建矢量&lt; vector&lt; double&gt;&gt;矩阵具有分配而不是inizializ
- 将具有不同字段的结构转换为 uint8 的数组
- uint32, int16, uint8 .为什么这些常用的数据类型没有进入标准
- C 字符串比较“祝您好运”&gt;“再见”
- 如何将 uint8 列表转换为其相应的有符号值
- 为什么将此对向量&lt; map&lt; int,int&gt;&gt;中的地图进行更新.失败
- 兼容的声明 __attribute__ ((节( ".abc.dfe" ))) 常量易失性 uint8 属性变量 = 0;- 符合MISRA标准
- 如何将UINT8*施放到UINT32
- 如何将元素从 Swift 中的 [UnsafeMutablePointer<UInt8>] 转换为 C++ 中的 UInt8 *
- 从字符串转换为 uint8,反之亦然