How to convert vector iterator to int in C++

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

    You just dereference the iterator like this

    index = *it;
    

    However you should first see if you actually found something

    it = find(myvector.begin(), myvector.end(), x);  
    if (it != myvector.end())
    {
        index = *it;
    }
    

    To find the index in that the match was found, you can use subtraction of the found pointer from the start of the vector.

    it = find(myvector.begin(), myvector.end(), x);  
    if (it != myvector.end())
    {
        index = it - myvector.begin();  // Index from start of vector
    }
    

    Also, hopefully in your actual code you defined x, as in the snippet you showed x is uninitialized so this will result in undefined behavior.

提交回复
热议问题