with vector, how to make a function that returns the container number

I have a vector, say, DL.

And i have a function

1
2
3
4
5
6
int ChooseVertex(const vector<int>& DL){
	// given DL, return the vertex with minimum element
	vector<int>::iterator min_DL;
	min_DL = min_element(DL.begin(), DL.end());
	return min_DL; 
}


when i called the function like this

v = ChooseVertex(DL);

I got an error on line 4,
error C2679: binary '=' : no operator found which takes a right-hand operand of type 'std::_Vector_const_iterator<_Ty,_Alloc>' (or there is no acceptable conversion)


Does anybody know the reason? Thank you in advance. :)
Last edited on
because you have a const vector, you need to use a const_iterator:

 
vector<int>::const_iterator min_DL;   // <- 


Also note that you can't return an iterator as an int, so you'll probably have to change the return type from int to vector<int>::const_iterator
Thank you.

But I need to return 'min_DL' as integer because in the main() I will store this return value in a vector<int> container.

Is this possible?
not with iterators. No way to get an integer index from an iterator as far as I know.

You'll have to use min_element another way, and use some pointer math:

1
2
3
4
5
int ChooseVertex(const vector<int>& DL)
{
    const int* start = &DL[0];
    return min_element(start,start + DL.size()) - start;
}
wow!! it works!! you are so smart!

But i have another question.

what does &DL[0] mean? Is this indicate the address of the first element of vector DL?

I thought in vector container, the index begins from 1, unlike array whose index begins from 0.

More generically

1
2
3
#include <iterator>  // std::distance

return std::distance( DL.begin(), std::min_element( DL.begin(), DL.end() );


This is container and iterator agnostic. Above works only for vector.
oh crap. Nice.

I forgot <iterator> existed XD

EDIT: but wait... wouldn't that step through the vector element at a time?

EDIT 2: of course! Unless it's specialized!

templates are awesome
Last edited on
thank you guys. You are awesome!
Topic archived. No new replies allowed.