Need to return element of an iterator.

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);
}
Last edited on
Can you rephrase your question? I'm not sure if you are just looking for a simple change from (*ip) to ip.
Or even from (*ip) to (&ip)?
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.
I'm not sure how to do this in C++, but I would imagine your problem can be solved with a cast. What error do you get when you remove the *?
Last edited on
A cast makes sense, but i'm not sure what to cast to? int to ... ?

Here are the errors when I remove the dereference operator:


Error 1 error C2440: 'return' : cannot convert from 'std::_Vector_iterator<std::_Vector_val<std::_Simple_types<int>>>' to 'int'

2 IntelliSense: no suitable conversion function from "std::_Vector_iterator<std::_Vector_val<std::_Simple_types<int>>>" to "int" exists
Last edited on
Could it be a typedef issue?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#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 )
{
    const auto iter = std::find( std::begin(container), std::end(container), number ) ;
    return iter != container.end() ? iter - container.begin() : -1 ;
}
Last edited on
JLBorges, should line 10 be if( number == *iter ) return iter - container.begin() ;?
Yes, thanks. Corrected.
Topic archived. No new replies allowed.