Search code examples
c++algorithmiteratorfindstdvector

Iterator with find() in c++


I want to know how to get the position of the result when I use the find() command.

My code have the command:

vector<int>::iterator result = find(list_of_number.begin(), list_of_number.end(), number_need_to_find);
    cout << result;

And it give me the error as follow:

error: invalid cast from type 'std::vector<int>::iterator' to type 'int'
   57 |     cout << (int)result;
      |             ^~~~~~~~~~~

Solution

  • You are doing it wrong. The std::find returns the iterator pointing to the element if it has been found, otherwise, it returns the end iterator. Therefore a check needs to be done prior to using the iterator result.

    Secondly, the

    std::cout << result;
    

    trying to print the iterator itself. You should have instead checked the iterator for list_of_number.end() and (if found) use std::distance to find the position of the found element in the list_of_number.

    #include <iterator>   // std::distance
    
    int main()
    {
        std::vector<int> list_of_number{1, 2, 3, 4};
    
        // if init-statement since C++17
        if (auto iter = std::find(
            list_of_number.cbegin(), list_of_number.cend(), 3); // find the element using std::find
            iter != list_of_number.cend())                      // if found (i.e. iter is not the end of vector iterator)
        {
            std::cout << std::distance(list_of_number.cbegin(), iter); // use  std::distance for finding the position
        }
        else
        {
            std::cout << "Not found\n";
        }
    }