要在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;
}
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;
}
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;
}