Standard Template Library: Using the Vector find() Method

What is the C++ STL Vector find() Method?

The C++ STL Vector find() method is a built-in function in the C++ Standard Template Library (STL) that is used to search for a particular element in a vector container. It returns an iterator pointing to the first occurrence of the specified element in the vector or returns the end iterator if the element is not found.


Syntax

The syntax of the C++ STL Vector find() method is as follows:

std::vector<T>::iterator find (const T& val);

Here, T is the data type of the vector elements, and val is the value of the element to search for.


How to Use it

To use the C++ STL Vector find() method, you need to follow these steps:

  1. Create a vector container and initialize it with some elements.
  2. Call the find() method on the vector, passing the element's value to search for as an argument.
  3. Check the return value of the find() method to see if it points to the end iterator.
  4. If the iterator points to the end of the vector, then the element was not found. Otherwise, the iterator points to the first occurrence of the element in the vector.



Program Code Snippet Example

Here's an example program that demonstrates how to use the C++ STL Vector find() method:

#include <iostream>
#include <vector>
#include <algorithm>

int main()
{
   // Create a vector container and initialize it
   std::vector<int> vec = { 1, 2, 3, 4, 5 };

   // Search for the element '3' in the vector
   auto it = std::find(vec.begin(), vec.end(), 3);

   // Check if the element was found or not
   if (it != vec.end())
   {
      std::cout << "Element found at position " << it - vec.begin() << std::endl;
   }
   else
   {
      std::cout << "Element not found" << std::endl;
   }

   return 0;
}

In this example, we create a vector container vec and initialize it with some elements.

Then, we call the find() method on the vector, passing the value 3 as an argument. The find() method returns an iterator pointing to the first occurrence of 3 in the vector, which we store in the variable it.

We then check if the iterator is pointing to the end of the vector or not.

If not, we print the element's position in the vector. If it is, we print a message saying the element was not found.




Given a vector vec of integers, find the first occurrence of 5 and replace it with the number 10 using the find() method. Then, print the modified vector.