How to convert vector iterator to int in C++

前端 未结 3 1790
暗喜
暗喜 2021-02-04 00:53

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 :

3条回答
  •  滥情空心
    2021-02-04 01:32

    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.

提交回复
热议问题