STL algorithms
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.
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.
std::cin
.std::cin
inside a while loop.std::find
.end()
of the name list.