std find
suggest changetemplate <class InputIterator, class T>
InputIterator find (InputIterator first, InputIterator last, const T& val);
Effects
Finds the first occurrence of val within the range [first, last)
Parameters
first
=> iterator pointing to the beginning of the range last
=> iterator pointing to the end of the range val
=> The value to find within the range
Return
An iterator that points to the first element within the range that is equal(==) to val, the iterator points to last if val is not found.
Example
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
int main(int argc, const char * argv[]) {
//create a vector
vector<int> intVec {4, 6, 8, 9, 10, 30, 55,100, 45, 2, 4, 7, 9, 43, 48};
//define iterators
vector<int>::iterator itr_9;
vector<int>::iterator itr_43;
vector<int>::iterator itr_50;
//calling find
itr_9 = find(intVec.begin(), intVec.end(), 9); //occurs twice
itr_43 = find(intVec.begin(), intVec.end(), 43); //occurs once
//a value not in the vector
itr_50 = find(intVec.begin(), intVec.end(), 50); //does not occur
cout << "first occurence of: " << *itr_9 << endl;
cout << "only occurence of: " << *itr_43 << Lendl;
/*
let's prove that itr_9 is pointing to the first occurence
of 9 by looking at the element after 9, which should be 10
not 43
*/
cout << "element after first 9: " << *(itr_9 + 1) << ends;
/*
to avoid dereferencing intVec.end(), lets look at the
element right before the end
*/
cout << "last element: " << *(itr_50 - 1) << endl;
return 0;
}
Output
first occurence of: 9
only occurence of: 43
element after first 9: 10
last element: 48
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents
2 Literals
9 Arrays
10 Flow control
12 Loops
15 keywords
17 auto keyword
18 Pointers
21 std::string
22 Enumeration
24 std::vector
25 std::array
26 std::pair
27 std::map
30 std::any
31 std::variant
36 std::iomanip
37 Iterators
38 Basic I/O
39 File I/O
40 Streams
44 References
45 Polymorphism
52 Unions
53 Templates
54 Namespaces
57 Lambdas
58 Threading
60 Preprocessor
61 SFINAE
63 RAII
64 Exceptions
68 Sorting
75 Pimpl idiom
76 Copy elision
79 Singleton
82 Type erasure
85 RTTI
88 Scopes
89 Atomic types
91 constexpr
99 Type traits
103 Attributes
105 Profiling
108 Recursion
109 Callable objects
112 Inline functions
114 Header files
117 Parameter packs
118 Iteration
119 type deduction
121 Build systems
123 Type inference
126 Alignment
127 Inline variables
134 Optimization
135 Semaphore
137 Debugging
140 Mutexes
141 Recursive mutex
142 Unit testing
143 decltype
144 Digit separators
145 C++ Containers
147 Contributors