For problems where either pseudo-code or C++ code is required, you may simply in
ID: 3869835 • Letter: F
Question
For problems where either pseudo-code or C++ code is required, you may simply include the algorithm written as pseudo-code without being tested as long as the logic is clear and can be easily understood by the grader
Implement the STL find routine that returns the iterator containing the first occurrence of x in the range that begins at start and extends up to, but not including end. If x is not found, end is returned. This is a nonclass (global function) with signature:
template <typename Iterator, typename Object>
Iterator find(Iterator start, Iterator end, const Object& x)
Explanation / Answer
#include <iostream>
#include <vector>
#include <iterator>
template<typename Iterator, typename Object>
Iterator find(Iterator start, Iterator end, const Object& value)
{
//while start not equals end loop
while(start != end)
{
//if we found value in between just return the iterator
//to that value
if(*start == value) return start;
//else continue loop and increment start
start++;
}
//if element is not present in the container return iterator to end
return end;
}
int main(void)
{
int n1 = 3;
std::vector<int> vec;
for (int i = 0; i < 5; ++i)
vec.push_back(i);
std::vector<int>::iterator result = find(vec.begin(), vec.end(), n1);
if (result != vec.end()) std::cout << "vec have: " << n1 << std::endl;
else std::cout << "vec don't have: " << n1 << std::endl;
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.