使用`find()`的迭代器在C++中。

huangapple go评论77阅读模式
英文:

Iterator with find() in c++

问题

我想知道当我使用find()命令时,如何获取结果的位置。

我的代码包含了以下命令:

vector<int>::iterator result = find(list_of_number.begin(), list_of_number.end(), number_need_to_find);
cout << result;

但它给我返回了以下错误:

错误: 从类型 'std::vector<int>::iterator' 到类型 'int' 的无效转换
   57 |     cout << (int)result;
英文:

I want to know how to get the position of the result when I use the find() command.

My code have the command:

vector&lt;int&gt;::iterator result = find(list_of_number.begin(), list_of_number.end(), number_need_to_find);
    cout &lt;&lt; result;

And it give me the error as follow:

error: invalid cast from type &#39;std::vector&lt;int&gt;::iterator&#39; to type &#39;int&#39;
   57 |     cout &lt;&lt; (int)result;
      |             ^~~~~~~~~~~

答案1

得分: 2

你的做法有问题。std::find 返回指向找到的元素的迭代器,如果未找到,则返回尾迭代器。因此,在使用迭代器 result 之前需要进行检查。

其次,这行代码:

std::cout << result;

尝试打印迭代器本身。你应该改为检查迭代器是否等于 list_of_number.end(),如果相等,然后使用 std::distance 来找到在 list_of_number 中找到的元素的位置。

#include <iterator>   // std::distance

int main()
{
    std::vector<int> list_of_number{1, 2, 3, 4};

    // 自 C++17 起支持 init-statement
    if (auto iter = std::find(
        list_of_number.cbegin(), list_of_number.cend(), 3); // 使用 std::find 查找元素
        iter != list_of_number.cend())                      // 如果找到(即 iter 不是尾迭代器)
    {
        std::cout << std::distance(list_of_number.cbegin(), iter); // 使用 std::distance 找到位置
    }
    else
    {
        std::cout << "未找到\n";
    }
}
英文:

You are doing it wrong. The std::find returns the iterator pointing to the element if it has been found, otherwise, it returns the end iterator. Therefore a check needs to be done prior to using the iterator result.

Secondly, the

std::cout &lt;&lt; result;

trying to print the iterator itself. You should have instead checked the iterator for list_of_number.end() and (if found) use std::distance to find the position of the found element in the list_of_number.

#include &lt;iterator&gt;   // std::distance

int main()
{
    std::vector&lt;int&gt; list_of_number{1, 2, 3, 4};

    // if init-statement since C++17
    if (auto iter = std::find(
        list_of_number.cbegin(), list_of_number.cend(), 3); // find the element using std::find
        iter != list_of_number.cend())                      // if found (i.e. iter is not the end of vector iterator)
    {
        std::cout &lt;&lt; std::distance(list_of_number.cbegin(), iter); // use  std::distance for finding the position
    }
    else
    {
        std::cout &lt;&lt; &quot;Not found\n&quot;;
    }
}

huangapple
  • 本文由 发表于 2023年7月13日 19:01:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/76678622.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定