c++ - C++ 在向量中找到 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;
这表示 find 工作正常,它告诉您它在第一个位置找到了数字,为此,it != end
(end 不是有效元素,而是标记容器结束的有效迭代器。 )
在这里试试
推荐阅读
- python - 如何展平具有相同 id 的多行的 pandas 数据框
- google-apps-script - 每周更新列中的新行
- django - 查找 Django API 瓶颈
- java - 等待来自 vertx 中多个可观察对象的响应
- haskell - 实现采用 [Maybe a] 并返回 Maybe [a] 的函数的更好方法
- ios - 来自“[任何]?”的演员表 到不相关的类型 '[String : String?]' 总是失败的问题
- grails - Grails spring security userDetailService 导入服务
- python - 基于值的python dict键顺序 - 递归解决方案
- python - 将特定内容从一个 word doc 复制到另一个
- python-3.x - tkcalendar:更改 DateEntry() 的输出配置