Funny Programmer
Funny Programmer

Reputation: 84

How to check C++ lists for specific values at a specific index

I have a list

list<int>generic_list;

I then append a random number to the list

rand_num = rand();
generic_list.push_front(rand_num);

I then check the list for if it has a value in it

find(generic_list.begin(), generic_list.end(), "generic string");

Once I have proven that it is in the list how do I find the specific index it's at?

Upvotes: 1

Views: 496

Answers (1)

A M
A M

Reputation: 15267

You can solve this problem with std::distance. This will return the number of "hops" from the begin of your list to the found item.

As you can read in the desciption of the std::find function, this will return an iterator to the found element. (end() if nothing could be found).

Then you can simply std::distance to show get the index.

Please see the example code below:

#include <iostream>
#include <list>
#include <iterator>
#include <algorithm>

int main() {
    // Define a list and populate it with some numbers
    std::list<int> myList{0,1,2,3,4,5,6,7,8,9,10};

    // Look for a value in the list
    std::list<int>::iterator result = std::find(myList.begin(), myList.end(), 7);

    // And, if found, calculate the index and show it on the display
    if (result != myList.end())
        std::cout << "Index: " << std::distance(myList.begin(), result) << '\n';
}

Upvotes: 1

Related Questions