How to convert vector iterator to int in C++

前端 未结 3 1786
暗喜
暗喜 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:19

    If you want the index of the found element, then that's the distance from the start of the sequence:

    index = it - myvector.begin();
    

    or, since C++11,

    index = std::distance(myvector.begin(), it);
    

    which will work with any forward iterator type, not just random-access ones like those from a vector.

提交回复
热议问题