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

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

Iterator with find() in c++

问题

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

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

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

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

  1. 错误: 从类型 'std::vector<int>::iterator' 到类型 'int' 的无效转换
  2. 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:

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

And it give me the error as follow:

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

答案1

得分: 2

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

其次,这行代码:

  1. std::cout << result;

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

  1. #include <iterator> // std::distance
  2. int main()
  3. {
  4. std::vector<int> list_of_number{1, 2, 3, 4};
  5. // 自 C++17 起支持 init-statement
  6. if (auto iter = std::find(
  7. list_of_number.cbegin(), list_of_number.cend(), 3); // 使用 std::find 查找元素
  8. iter != list_of_number.cend()) // 如果找到(即 iter 不是尾迭代器)
  9. {
  10. std::cout << std::distance(list_of_number.cbegin(), iter); // 使用 std::distance 找到位置
  11. }
  12. else
  13. {
  14. std::cout << "未找到\n";
  15. }
  16. }
英文:

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

  1. 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.

  1. #include &lt;iterator&gt; // std::distance
  2. int main()
  3. {
  4. std::vector&lt;int&gt; list_of_number{1, 2, 3, 4};
  5. // if init-statement since C++17
  6. if (auto iter = std::find(
  7. list_of_number.cbegin(), list_of_number.cend(), 3); // find the element using std::find
  8. iter != list_of_number.cend()) // if found (i.e. iter is not the end of vector iterator)
  9. {
  10. std::cout &lt;&lt; std::distance(list_of_number.cbegin(), iter); // use std::distance for finding the position
  11. }
  12. else
  13. {
  14. std::cout &lt;&lt; &quot;Not found\n&quot;;
  15. }
  16. }

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:

确定