Hello - I need this loop to return the element of the iterator, not the value. Can anyone point me in the right direction?
1 2 3 4 5 6 7 8 9 10 11
int vectorsoo::check(int number)
{
for (vector<int>::iterator ip = container.begin(); ip != container.end(); ++ip)
{
if (number == (*ip))
{
return (*ip); //needs to return the address
}
}
return (-1);
}
If the int number equals the value in *ip, I would like to know at which element in the vector this occurs. When I remove the dereference operator, I get an error.
#include <vector>
#include <algorithm>
std::vector<int> container { 0, 1, 2, 3, 4, 5 } ;
// return position of element == number, or -1 if not found
int check1( int number )
{
for( std::vector<int>::iterator iter = container.begin() ; iter != container.end() ; ++iter )
if( number == *iter ) return iter - container.begin() ;
return -1 ;
}
// return position of element == number, or -1 if not found
int check2( int number )
{
for( std::vector<int>::const_iterator iter = container.cbegin() ; iter != container.cend() ; ++iter )
if( number == *iter ) return iter - container.cbegin() ;
return -1 ;
}
// return position of element == number, or -1 if not found
int check3( int number )
{
for( std::size_t i = 0 ; i < container.size() ; ++i )
if( number == container[i] ) return i ;
return -1 ;
}
// return position of element == number, or -1 if not found
int check4( int number )
{
constauto iter = std::find( std::begin(container), std::end(container), number ) ;
return iter != container.end() ? iter - container.begin() : -1 ;
}