Reputation: 1183
I'm new to C++ so this might be a simple problem but I'm working my way through the C++ book by Stanley Lippman and there's this exercise where you're supposed to write a very basic search function for a vector of ints. Basically just incrementing the iterator until you find what you're looking for and then return an iterator to the element.
My first question is, in the book it says "Don't forget to handle the case where the element can't be found" - what would you do in a case like that? In java I would return a null but I guess that's not okay in C++ (a nullptr?)?
Second question is, why doesn't it work? I thought that if I can't find it, I'll just return the end()-iterator as it's one element behind the last one (thus, not pointing to an element in the vector) but I can't get the comparing to work, it says "Found!" on every number when I try it.
#include <vector>
#include <iterator>
#include <iostream>
const std::vector<int>::iterator
search (std::vector<int> v, const int find) {
auto beg = v.begin();
const auto end = v.end();
while (beg != end) {
if (*beg == find) {
return beg;
}
++beg;
}
return beg; // This can only be reached if beg = v.end()?
}
int
main () {
std::vector<int> v;
v.insert(v.end(), 2);
v.insert(v.end(), 5);
v.insert(v.end(), 10);
v.insert(v.end(), 7);
v.insert(v.end(), 12);
for (int i = 0; i < 16; ++i) {
std::vector<int>::iterator b = search(v, i);
std::cout << i;
if (std::distance(b, v.end()) == 0) {
std::cout << " not found!";
} else {
std::cout << " found!";
}
std::cout << std::endl;
}
return 0;
}
with output as follows:
$ ./a.exe
0 found!
1 found!
2 found!
3 found!
4 found!
5 found!
6 found!
7 found!
8 found!
9 found!
10 found!
11 found!
12 found!
13 found!
14 found!
15 found!
Upvotes: 2
Views: 111
Reputation: 9648
When you call the function, you are passing the vector by value, so it makes a copy. The iterators for this copy will not be the same as the ones in the original vector so the comparison fails. To fix this, pass the vector by constant reference:
search( const std::vector<int>& v, const int find )
To answer your first question, yes, returning the end()
iterator is how you indicate the value was not found. This is how std::find()
works:
If no such element is found, the function returns last.
Upvotes: 4