Searching: std::find
In the Loops lesson, you searched with a loop: a variable position started at -1, and when the loop found the element, it stored its index and ended with break. The algorithm std::find searches for you. It looks for the first element that is equal to a value:
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
int main() {
std::vector<std::string> backpack = {"rope", "torch", "potion", "map"};
auto it = std::find(backpack.begin(), backpack.end(), "potion");
if (it == backpack.end()) {
std::cout << "No potion" << std::endl;
} else {
std::cout << "Found: " << *it << std::endl;
std::cout << "Index: " << it - backpack.begin() << std::endl;
}
return 0;
}This prints:
Found: potion
Index: 2std::find doesn't return the element or its index, but an iterator: the position of the element in the vector. You met iterators at the start of the lesson, as begin() and end(). Here's what you can do with the one that std::find returns:
- Check whether something was found. When the value isn't in the vector,
std::findreturnsend(), the position after the last element. That's how algorithms say “not found”, like the-1in your loop. - Read the element with
*it. An iterator works much like a pointer:*itis the element at its position, just as*pis the variable that a pointer points to. And you can change the element through it:*it = "bottle";changes the element in the vector. - Get the index with
it - backpack.begin(): how many positions the iterator is from the beginning.
Use *it only after you have checked that it isn't end(). There's no element at end(), and reading it is the same kind of mistake as reading through nullptr.
The type of this iterator is long, std::vector<std::string>::iterator. You could write std::vector<std::string>::iterator it = …, but with auto, which you know from the lesson on maps, the compiler works out the type itself. In error messages, you will see iterators under the library's own names. For example, std::cout << it without the asterisk doesn't compile, because an iterator can't be printed: error: invalid operands to binary expression ('ostream' (aka 'basic_ostream<char>') and 'std::__wrap_iter<std::string *>').
Instructions
- 1
In place of the comment, look for
"potion"inbackpackwithstd::find. When it's there, print its index, worked out from the iterator, asPotion at index 2. When it isn't, printNo potion. Keep the line with the backpack as it is: the exercise also runs your program with other items. - 2
The hero drinks the potion, and only the bottle is left. In the branch where the potion was found, below the line that prints its index, change the element to
"bottle"through the iterator. The program then printsBackpack: rope torch bottle map key.