TL ; DR:
A vector has no contains method. Use find(v.begin(), v.end(), x) instead. It returns v.end() when x isn't there.
vector<string> colors = {"red", "green", "blue"};
if (find(colors.begin(), colors.end(), "red") != colors.end()) {
cout << "We have red" << endl;
}
if (find(colors.begin(), colors.end(), "pink") == colors.end()) {
cout << "No pink yet" << endl;
}
Full lesson:
Often you need to know if a vector holds some value. Is this name on the guest list? Is this item in the cart?
The find function from <algorithm> answers that. Give it a start position, an end position and the value.
It compares the items between the two positions with the value. It returns the position of the first match.
If nothing matches, it returns the end position, v.end(). That spot is just past the last item.
So compare the result with v.end(). Not equal means found, and equal means missing. The comparison is a bool, so it fits right into an if:
vector<string> cart = {"milk", "bread"};
if (find(cart.begin(), cart.end(), "milk") != cart.end()) {
cout << "Milk is in the cart" << endl;
}
Text must match exactly. Looking for "Red" finds nothing, because the vector has "red".
Your task
bag holds what is packed for a hike.
If "water" is in bag, print Water is packed. If "tent" is not in bag, print Pack a tent.
Expected output:
Water is packed
Pack a tentFree plan: 30 tutor messages. PRO is unlimited.
