Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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";
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading