1: //find_if1a.cpp 3: #include <iostream> 4: #include <vector> 5: #include <algorithm> 6: using namespace std; 8: /** 9: Determines if an integer is divisible by 3. 10: Pre:\n n contains an integer. 11: Post:\n Returns true if n is divisible by 3, and otherwise false. 12: */ 13: bool isDivisibleByThree 14: ( 15: int n //in 16: ) 17: { 18: return (n%3 == 0); 19: } 21: int main() 22: { 23: cout << "\nThis program illustrates the use of the STL find_if() " 24: "algorithm\nto find an integer divisible by 3 in a vector of " 25: "integers.\n"; 26: cout << "Press Enter to continue ... "; cin.ignore(80, '\n'); 28: int a[] = {1, 2, 4, 5, 7, 12, 9, 8, 3, 6}; 29: vector<int> v(a, a+10); 30: cout << "\nHere are the contents of v:\n"; 31: for (vector<int>::size_type i=0; i<v.size(); i++) 32: cout << v.at(i) << " "; 33: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n'); 35: vector<int>::iterator p; 36: p = find_if(v.begin(), v.end(), isDivisibleByThree); 37: if (p == v.end()) 38: cout << "\nThere are no values divisible by 3.\n"; 39: else 40: cout << "\nThe first value in the sequence divisible by 3 is " 41: << *p << ",\nwhich was found at location " 42: << (int)(p-v.begin()+1) << ".\n"; 43: cout << "Press Enter to continue ... "; cin.ignore(80, '\n'); 44: }