STL algorithms

10.5 - Find


The std::find method can be used to find the position of an element inside a container. It takes (begin, end, target) as its argument and returns an iterator to the target if it is in the container. The position of the target can then be found using std::distance with begin.

auto search = std::find(v.begin(), v.end(), target);
std::cout << std::distance(v.begin(), search) << std::endl;

In case the target is not in the container, std::find will return end. This means std::find can be used to check if the target exist in the container or not.

auto search = std::find(v.begin(), v.end(), target);
if (search == v.end()) {
    // target does not exist in v.
}
else {
    // target exists in v.
}

Use the std::find method to check if an element exist in a container.

Task

Write a program which takes a single name and then a list of names in another line, then prints out the position of the name in the list if it exist.

  • Get the target name using std::cin.
  • Get the name list using std::cin inside a while loop.
  • Get the iterator to the name using std::find.
  • Check if the target name exist in the name list by comparing it with the end() of the name list.
    • If the target exists, print it.
#include <iostream> #include <vector> #include <string> #include <algorithm> int main() { }