C++在矢量<uint8_t>中查找uint8_t

C++ finding uint8_t in vector<uint8_t>

本文关键字:uint8 gt 查找 C++ lt      更新时间:2023-10-16

我有以下简单的代码。在这种情况下,我声明一个向量并用一个值 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 不是有效元素,而是标记容器末尾的有效迭代器。

在这里尝试一下