Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert vector iterator to int in C++

I am looking for an element in a C++ vector, and when I find it, I want to get found element's index in a numerical form(integer, float).

My naive attempt is this :

int x; int index; vector<int> myvector; vector<int>::iterator it; it = find(myvector.begin(), myvector.end(), x);   index = (int) * it; 

This code is giving error. Can you tell me how I can convert iterator to int(if possible), or can you tell me how I can get found element's index in other way? Thanks.

like image 418
jason Avatar asked Nov 18 '14 13:11

jason


1 Answers

You need to use standard function std::distance

index = std::distance( myvector.begin(), it );  if ( index < myvector.size() ) {     // do something with the vector element with that index } 

Try always to use std::distance even with random access iterators. This function is available in the new and old C++ Standards.

like image 117
Vlad from Moscow Avatar answered Sep 19 '22 10:09

Vlad from Moscow