要在vector中查找元素及其位置,可以使用以下方法:
- 使用find()函数:可以使用STL中的find()函数来查找元素在vector中的位置。例如,要查找值为x的元素在vector中的位置,可以使用以下代码:
auto it = find(vec.begin(), vec.end(), x);
if (it != vec.end()) {
int index = distance(vec.begin(), it);
cout << "Element found at position: " << index << endl;
} else {
cout << "Element not found" << endl;
}
- 使用find_if()函数:如果要查找满足特定条件的元素在vector中的位置,可以使用find_if()函数。例如,要查找大于10的第一个元素在vector中的位置,可以使用以下代码:
auto it = find_if(vec.begin(), vec.end(), [](int num){ return num > 10; });
if (it != vec.end()) {
int index = distance(vec.begin(), it);
cout << "Element found at position: " << index << endl;
} else {
cout << "Element not found" << endl;
}
- 手动遍历vector:也可以手动遍历vector来查找元素及其位置。例如,要查找值为x的元素在vector中的位置,可以使用以下代码:
int index = -1;
for (int i = 0; i < vec.size(); i++) {
if (vec[i] == x) {
index = i;
break;
}
}
if (index != -1) {
cout << "Element found at position: " << index << endl;
} else {
cout << "Element not found" << endl;
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,请发送邮件至 55@qq.com 举报,一经查实,本站将立刻删除。转转请注明出处:https://www.szhjjp.com/n/944999.html