I have a method to find number in range of iterator like below. I want it has reference parameter and return reference of iterator.
// find number in range of begin and end, if number found return reference of iterator, throw exception otherwise
vector<int>::iterator &find_int(vector<int>::iterator &begin, vector<int>::iterator &end, int &number)
{
for (; begin != end; ++begin)
{
if (*begin == number)
{
return begin;
}
}
throw "not found";
}
I want to call this method as following code but it can’t compile.
vector<int>::iterator i5 = find_int(vi1.begin(), vi1.end(), 5);
I want to know how can I call find_int method ?
Update
Error message when compile the code
C:\Windows\system32\cmd.exe /c g++ c:\cpp\ch9.cpp -o c:\cpp\ch9.exe
c:\cpp\ch9.cpp: In function 'int main()':
c:\cpp\ch9.cpp:41:63: error: invalid initialization of non-const reference of ty
pe 'std::vector<int>::iterator& {aka __gnu_cxx::__normal_iterator<int*, std::vec
tor<int> >&}' from an rvalue of type 'std::vector<int>::iterator {aka __gnu_cxx:
:__normal_iterator<int*, std::vector<int> >}'
c:\cpp\ch9.cpp:30:24: error: in passing argument 1 of 'std::vector<int>::iterato
r& find_int(std::vector<int>::iterator&, std::vector<int>::iterator&, int&)'
shell returned 1
Hit any key to close this window...
That function really shouldn’t be taking
iterator&‘s (or theint&1) anyway. It should take the arguments by value, and return the iterator by value.Even if you didn’t get a compiler error because of the int literal you’re trying to pass it (
5) where it expects anint&1, the reason you can’t call it the way you’re doing is because you would be passing a reference to a temporary value, then getting a reference to that temporary through the return value of the function, and by the next line of code, the reference would refer to a destroyed object.You can call it like this:
Note that
&pos == &beg.However, if this isn’t a didactic exercise, I would recommend to do what shuttle87 suggested, which is to use
std::find.1 Thanks Ghita for pointing this out.