首页 > 解决方案 > 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;

}

标签: c++algorithmfind

解决方案


你确定它不起作用吗?

我刚试过:

#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 不是有效元素,而是标记容器结束的有效迭代器。 )

在这里试试


推荐阅读