英文:
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<int>::iterator result = find(list_of_number.begin(), list_of_number.end(), number_need_to_find);
cout << result;
And it give me the error as follow:
error: invalid cast from type 'std::vector<int>::iterator' to type 'int'
57 | cout << (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 << 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 <iterator> // std::distance
int main()
{
std::vector<int> 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 << std::distance(list_of_number.cbegin(), iter); // use std::distance for finding the position
}
else
{
std::cout << "Not found\n";
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论