here's an example program using the find() algorithm to locate the position of a specified value in a vector:
#include <vector>
#include <algorithm>
int main() {
// Create a vector of integers
vector<int> vec = { 5, 2, 7, 9, 1, 8 };
// Find the position of the value 7 in the vector
auto it = find(vec.begin(), vec.end(), 7);
// Check if the value was found and print the position
if (it != vec.end()) {
cout << "The position of the value 7 is: " << distance(vec.begin(), it) << endl;
} else {
cout << "The value 7 was not found in the vector." << endl;
}
return 0;
}
Output:
The position of the value 7 is: 2
In this program, we first create a vector of integers with some random values. We then use the find() algorithm from the <algorithm> header to find the position of the value 7 in the vector.
The find() algorithm returns an iterator pointing to the first occurrence of the value in the range [first, last]. If the value is not found, it returns an iterator pointing to the end of the range.
We then check if the value was found by comparing the iterator to the end of the vector. If the value was found, we use the distance() function to calculate the position of the iterator from the beginning of the vector, which gives us the position of the value in the vector. If the value was not found, we simply print a message stating that it was not found.
No comments:
Post a Comment
If you have any doubts, please let me know